OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 180 | Go to most recent revision | 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");
184
            String productName = rowItem.getString("NOM").trim().length() == 0 ? "Ligne" : rowItem.getString("NOM");
177 ilm 185
 
180 ilm 186
            final BigDecimal pHT, pTTC, totalHTLigne, totalTTCLigne;
187
            SQLRowAccessor taxeItem = rowItem.getForeign("ID_TAXE");
182 ilm 188
            BigDecimal taxValue = new BigDecimal(taxeItem.getFloat("TAUX")).setScale(2, RoundingMode.HALF_UP);
180 ilm 189
            if (rowItem.getInt("NIVEAU") != 1) {
190
                pHT = BigDecimal.ZERO;
191
                pTTC = BigDecimal.ZERO;
192
                totalHTLigne = BigDecimal.ZERO;
193
                totalTTCLigne = BigDecimal.ZERO;
194
            } else {
195
                pHT = rowItem.getBigDecimal("PV_HT");
196
                pTTC = pHT.multiply(taxValue.add(BigDecimal.ONE));
197
                totalHTLigne = rowItem.getBigDecimal("T_PV_HT");
198
                totalTTCLigne = rowItem.getBigDecimal("T_PV_TTC");
199
            }
177 ilm 200
 
180 ilm 201
            int idTaxe = taxeItem.getID();
202
            if (!taxes.containsKey(idTaxe)) {
203
                Tax t = new Tax(taxValue);
204
                taxes.put(idTaxe, t);
205
            }
206
            taxes.get(idTaxe).add(totalTTCLigne.subtract(totalHTLigne), totalHTLigne);
207
            BigDecimal qte = new BigDecimal(rowItem.getInt("QTE")).multiply(rowItem.getBigDecimal("QTE_UNITAIRE"));
208
 
177 ilm 209
            Element eLineItem = new Element("IncludedSupplyChainTradeLineItem", RAM_NS);
180 ilm 210
 
177 ilm 211
            // AssociatedDocumentLineDocument
212
            Element eAssociatedDocumentLineDocument = new Element("AssociatedDocumentLineDocument", RAM_NS);
213
            Element eLineID = new Element("LineID", RAM_NS);
180 ilm 214
            eLineID.setText(String.valueOf(lineID++));
177 ilm 215
            eAssociatedDocumentLineDocument.addContent(eLineID);
216
            eLineItem.addContent(eAssociatedDocumentLineDocument);
217
            // SpecifiedTradeProduct
218
            Element eSpecifiedTradeProduct = new Element("SpecifiedTradeProduct", RAM_NS);
219
            if (!productCode.isEmpty()) {
220
                Element eGlobalID = new Element("GlobalID", RAM_NS);
221
                if (productCode.length() > 40) {
222
                    // CHORUSPRO: this field is limited to 40 characters
223
                    productCode = productCode.substring(0, 40);
224
                }
225
                if (checkEAN13(productCode)) {
226
                    // 0088 : EAN
227
                    eGlobalID.setAttribute("schemeID", "0088");
228
                } else {
229
                    // 0197 : Not Known
230
                    eGlobalID.setAttribute("schemeID", "0197");
231
                }
232
                eGlobalID.setText(productCode);
233
                eSpecifiedTradeProduct.addContent(eGlobalID);
234
            }
235
            Element eName = new Element("Name", RAM_NS);
236
            eName.setText(productName);
237
            eSpecifiedTradeProduct.addContent(eName);
238
            eLineItem.addContent(eSpecifiedTradeProduct);
239
            //
240
            Element eSpecifiedLineTradeAgreement = new Element("SpecifiedLineTradeAgreement", RAM_NS);
241
            // Prix unitaire TTC
242
            Element eGrossPriceProductTradePrice = new Element("GrossPriceProductTradePrice", RAM_NS);
243
            Element eChargeAmount = new Element("ChargeAmount", RAM_NS);
180 ilm 244
            eChargeAmount.setText(formatAmount.format(pTTC));
177 ilm 245
            eGrossPriceProductTradePrice.addContent(eChargeAmount);
246
            Element eAppliedTradeAllowanceCharge = new Element("AppliedTradeAllowanceCharge", RAM_NS);
247
            Element eChargeIndicator = new Element("ChargeIndicator", RAM_NS);
180 ilm 248
            Element eIndicator = new Element("Indicator", UDT_NS);
177 ilm 249
            // pas de remise
250
            eIndicator.setText("false");
251
            eChargeIndicator.addContent(eIndicator);
252
            eAppliedTradeAllowanceCharge.addContent(eChargeIndicator);
253
 
254
            Element eActualAmount = new Element("ActualAmount", RAM_NS);
255
            // Montant de TVA (unitaire)
180 ilm 256
            eActualAmount.setText(formatAmount.format(pTTC.subtract(pHT)));
177 ilm 257
 
258
            eAppliedTradeAllowanceCharge.addContent(eActualAmount);
259
 
180 ilm 260
            // eGrossPriceProductTradePrice.addContent(eAppliedTradeAllowanceCharge);
177 ilm 261
 
262
            eSpecifiedLineTradeAgreement.addContent(eGrossPriceProductTradePrice);
263
            // Prix unitaire HT
264
            Element eNetPriceProductTradePrice = new Element("NetPriceProductTradePrice", RAM_NS);
265
            Element eChargeAmountHT = new Element("ChargeAmount", RAM_NS);
180 ilm 266
            eChargeAmountHT.setText(formatAmount.format(pHT));
177 ilm 267
 
268
            eNetPriceProductTradePrice.addContent(eChargeAmountHT);
269
            eSpecifiedLineTradeAgreement.addContent(eNetPriceProductTradePrice);
270
            eLineItem.addContent(eSpecifiedLineTradeAgreement);
271
 
272
            // Quantité
273
 
274
            Element eSpecifiedLineTradeDelivery = new Element("SpecifiedLineTradeDelivery", RAM_NS);
275
 
276
            // LTR = Liter (1 dm3), MTQ = cubic meter , KGM = Kilogram , MTR = Meter , C62 = Unit ,
277
            // TNE = Tonne
278
            // TODO : gerer les unités
279
            Element eBilledQuantity = new Element("BilledQuantity", RAM_NS);
280
            eBilledQuantity.setAttribute("unitCode", "C62");
281
            eBilledQuantity.setText(fQty.format(qte));
282
 
283
            eSpecifiedLineTradeDelivery.addContent(eBilledQuantity);
284
            eLineItem.addContent(eSpecifiedLineTradeDelivery);
285
 
286
            Element eSpecifiedLineTradeSettlement = new Element("SpecifiedLineTradeSettlement", RAM_NS);
287
            Element eApplicableTradeTaxt = new Element("ApplicableTradeTax", RAM_NS);
288
 
289
            Element eTypeCode = new Element("TypeCode", RAM_NS);
290
            eTypeCode.setText("VAT");
291
            eApplicableTradeTaxt.addContent(eTypeCode);
292
 
293
            // S = Taux de TVA standard
294
            // E = Exempté de TVA
295
            // AE = Autoliquidation de TVA
296
            // K = Autoliquidation pour cause de livraison intracommunautaire
297
            // G = Exempté de TVA pour Export hors UE
298
            // O = Hors du périmètre d'application de la TVA
299
            // L = Iles Canaries
300
            // M = Ceuta et Mellila
301
            // TODO : TVA 0
302
            Element eCategoryCode = new Element("CategoryCode", RAM_NS);
303
            eCategoryCode.setText("S");
304
            eApplicableTradeTaxt.addContent(eCategoryCode);
305
 
306
            Element eRateApplicablePercent = new Element("RateApplicablePercent", RAM_NS);
307
            // 20% -> 20.0
180 ilm 308
            eRateApplicablePercent.setText(formatAmount.format(taxValue));
177 ilm 309
            eApplicableTradeTaxt.addContent(eRateApplicablePercent);
310
 
311
            eSpecifiedLineTradeSettlement.addContent(eApplicableTradeTaxt);
312
 
313
            Element eSpecifiedTradeSettlementLineMonetarySummation = new Element("SpecifiedTradeSettlementLineMonetarySummation", RAM_NS);
314
            // Total HT
315
            Element eLineTotalAmount = new Element("LineTotalAmount", RAM_NS);
180 ilm 316
            eLineTotalAmount.setText(formatAmount.format(totalHTLigne));
177 ilm 317
            eSpecifiedTradeSettlementLineMonetarySummation.addContent(eLineTotalAmount);
318
            eSpecifiedLineTradeSettlement.addContent(eSpecifiedTradeSettlementLineMonetarySummation);
319
 
320
            eLineItem.addContent(eSpecifiedLineTradeSettlement);
321
            //
322
            eSupplyChainTradeTransaction.addContent(eLineItem);
323
        }
324
 
180 ilm 325
        root.addContent(ed);
326
        addApplicableHeader(societeRow, facture, eSupplyChainTradeTransaction, taxes.values());
177 ilm 327
 
180 ilm 328
        root.addContent(eSupplyChainTradeTransaction);
177 ilm 329
 
330
        final XMLOutputter xmlOutput = new XMLOutputter();
331
        xmlOutput.setFormat(Format.getPrettyFormat());
332
        return xmlOutput.outputString(doc);
333
    }
334
 
335
    public void addValue(Element parent, Element element, String value) {
336
        element.setText(value);
337
        parent.addContent(element);
338
    }
339
 
180 ilm 340
    private void addApplicableHeader(SQLRowAccessor rowSociete, SQLRowAccessor rowFacture, Element eSupplyChainTradeTransaction, Collection<Tax> taxes) {
177 ilm 341
        //
342
        // ApplicableHeaderTradeAgreement
343
        //
344
        final Element eApplicableHeaderTradeAgreement = new Element("ApplicableHeaderTradeAgreement", RAM_NS);
180 ilm 345
        addSupplierInfo(eApplicableHeaderTradeAgreement, rowSociete);
346
        addBuyerInfo(eApplicableHeaderTradeAgreement, rowFacture);
177 ilm 347
 
348
        String orderRef = "";
349
        String contractRef = "";
350
        // Date de livraison, facultative
180 ilm 351
        Date effectiveDeliveryDate = rowFacture.getDate("DATE").getTime();
352
        String invoiceNumber = rowFacture.getString("NUMERO");
177 ilm 353
        String currencyCode = "EUR";
180 ilm 354
        SQLRowAccessor foreignMdr = rowFacture.getForeign("ID_MODE_REGLEMENT");
355
        int ajours = foreignMdr.getInt("AJOURS");
356
        int lenjour = foreignMdr.getInt("LENJOUR");
357
        String dueDescription = (ajours > 0 ? "A " + ajours : "") + (lenjour > 0 ? " le " + lenjour : "");
358
        Date dueDate = ModeDeReglementSQLElement.calculDate(foreignMdr, rowFacture.getDate("DATE").getTime());
177 ilm 359
 
360
        final Element eBuyerOrderReferencedDocument = new Element("BuyerOrderReferencedDocument", RAM_NS);
361
        addValue(eBuyerOrderReferencedDocument, new Element("IssuerAssignedID", RAM_NS), orderRef);
362
        eApplicableHeaderTradeAgreement.addContent(eBuyerOrderReferencedDocument);
363
 
364
        final Element eContractReferencedDocument = new Element("ContractReferencedDocument", RAM_NS);
365
        addValue(eContractReferencedDocument, new Element("IssuerAssignedID", RAM_NS), contractRef);
366
 
367
        eApplicableHeaderTradeAgreement.addContent(eContractReferencedDocument);
368
        eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeAgreement);
369
 
370
        //
371
        // ApplicableHeaderTradeDelivery
372
        //
373
        final Element eApplicableHeaderTradeDelivery = new Element("ApplicableHeaderTradeDelivery", RAM_NS);
374
 
375
        // <ram:ShipToTradeParty>
376
        // <ram:PostalTradeAddress>
377
        // <ram:PostcodeCode>69001</ram:PostcodeCode>
378
        // <ram:LineOne>35 rue de la République</ram:LineOne>
379
        // <ram:CityName>Lyon</ram:CityName>
380
        // <ram:CountryID>FR</ram:CountryID>
381
        // </ram:PostalTradeAddress>
382
        // </ram:ShipToTradeParty>
383
        if (effectiveDeliveryDate != null) {
384
            // Date de livraison effective (facultative)
385
            final Element eActualDeliverySupplyChainEvent = new Element("ActualDeliverySupplyChainEvent", RAM_NS);
386
            final Element eOccurrenceDateTime = new Element("OccurrenceDateTime", RAM_NS);
387
            addDateTime(effectiveDeliveryDate, eOccurrenceDateTime);
388
            eActualDeliverySupplyChainEvent.addContent(eOccurrenceDateTime);
389
            eApplicableHeaderTradeDelivery.addContent(eActualDeliverySupplyChainEvent);
390
        }
391
        eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeDelivery);
392
 
393
        //
394
        // ApplicableHeaderTradeSettlement
395
        //
396
        final Element eApplicableHeaderTradeSettlement = new Element("ApplicableHeaderTradeSettlement", RAM_NS);
397
        addValue(eApplicableHeaderTradeSettlement, new Element("PaymentReference", RAM_NS), invoiceNumber);
398
        addValue(eApplicableHeaderTradeSettlement, new Element("InvoiceCurrencyCode", RAM_NS), currencyCode);
399
        final Element aSpecifiedTradeSettlementPaymentMeans = new Element("SpecifiedTradeSettlementPaymentMeans", RAM_NS);
180 ilm 400
        addValue(aSpecifiedTradeSettlementPaymentMeans, new Element("TypeCode", RAM_NS), "57");
177 ilm 401
 
402
        // <ram:TypeCode>30</ram:TypeCode>
403
        // <ram:Information>Virement sur compte Banque Fiducial</ram:Information>
404
        // <ram:PayeePartyCreditorFinancialAccount>
405
        // <ram:IBANID>FR2012421242124212421242124</ram:IBANID>
406
        // </ram:PayeePartyCreditorFinancialAccount>
407
        // <ram:PayeeSpecifiedCreditorFinancialInstitution>
408
        // <ram:BICID>FIDCFR21XXX</ram:BICID>
409
        // </ram:PayeeSpecifiedCreditorFinancialInstitution>
410
 
411
        eApplicableHeaderTradeSettlement.addContent(aSpecifiedTradeSettlementPaymentMeans);
412
        DecimalFormat format = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
413
        for (Tax t : taxes) {
414
            final Element aApplicableTradeTax = new Element("ApplicableTradeTax", RAM_NS);
415
            // Montant de la TVA
416
            addValue(aApplicableTradeTax, new Element("CalculatedAmount", RAM_NS), format.format(t.amount));
417
            // LOL
418
            addValue(aApplicableTradeTax, new Element("TypeCode", RAM_NS), "VAT");
419
            // montant HT sur lequel s'applique la TVA
420
            addValue(aApplicableTradeTax, new Element("BasisAmount", RAM_NS), format.format(t.basisAmount));
421
            // S = Taux de TVA standard
422
            // E = Exempté de TVA
423
            // AE = Autoliquidation de TVA
424
            // K = Autoliquidation pour cause de livraison intracommunautaire
425
            // G = Exempté de TVA pour Export hors UE
426
            // O = Hors du périmètre d'application de la TVA
427
            // L = Iles Canaries
428
            // M = Ceuta et Mellila
429
            // TODO : TVA 0
430
            addValue(aApplicableTradeTax, new Element("CategoryCode", RAM_NS), "S");
431
 
432
            // TODO : type de TVA :
433
            // 5 : Date de la facture (TVA sur DEBITS)
434
            // 29 : Date de livraison (TVA sur DEBITS)
435
            // 72 : Date de paiement (TVA sur ENCAISSEMENTS)
436
            addValue(aApplicableTradeTax, new Element("DueDateTypeCode", RAM_NS), "5");
437
 
438
            addValue(aApplicableTradeTax, new Element("RateApplicablePercent", RAM_NS), format.format(t.rate));
439
            eApplicableHeaderTradeSettlement.addContent(aApplicableTradeTax);
440
        }
441
 
442
        final Element eSpecifiedTradePaymentTerms = new Element("SpecifiedTradePaymentTerms", RAM_NS);
443
        addValue(eSpecifiedTradePaymentTerms, new Element("Description", RAM_NS), dueDescription);
444
 
445
        final Element eDueDateDateTime = new Element("DueDateDateTime", RAM_NS);
446
        addDateTime(dueDate, eDueDateDateTime);
447
        eSpecifiedTradePaymentTerms.addContent(eDueDateDateTime);
448
        eApplicableHeaderTradeSettlement.addContent(eSpecifiedTradePaymentTerms);
449
 
450
        final Element eSpecifiedTradeSettlementHeaderMonetarySummation = new Element("SpecifiedTradeSettlementHeaderMonetarySummation", RAM_NS);
180 ilm 451
        final Element eTotalHT = new Element("LineTotalAmount", RAM_NS);
452
        eTotalHT.setText(this.formatAmount.format(new BigDecimal(rowFacture.getLong("T_HT")).movePointLeft(2)));
453
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalHT);
177 ilm 454
 
180 ilm 455
        final Element eTotalBaseTVA = new Element("TaxBasisTotalAmount", RAM_NS);
456
 
457
        BigDecimal totalBaseTVA = BigDecimal.ZERO;
458
        for (Tax tax : taxes) {
459
            totalBaseTVA = totalBaseTVA.add(tax.basisAmount);
460
        }
461
        eTotalBaseTVA.setText(this.formatAmount.format(totalBaseTVA));
462
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalBaseTVA);
463
 
464
        final Element eTotalTVA = new Element("TaxTotalAmount", RAM_NS);
465
        eTotalTVA.setAttribute("currencyID", "EUR");
466
        eTotalTVA.setText(this.formatAmount.format(new BigDecimal(rowFacture.getLong("T_TVA")).movePointLeft(2)));
467
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalTVA);
468
 
469
        final Element eTotalTTC = new Element("GrandTotalAmount", RAM_NS);
470
        BigDecimal totalTTC = new BigDecimal(rowFacture.getLong("T_TTC")).movePointLeft(2);
471
        eTotalTTC.setText(this.formatAmount.format(totalTTC));
472
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalTTC);
473
 
474
        final Element eTotalPrepaid = new Element("TotalPrepaidAmount", RAM_NS);
475
        BigDecimal netApayer = new BigDecimal(rowFacture.getLong("NET_A_PAYER")).movePointLeft(2);
476
        eTotalPrepaid.setText(this.formatAmount.format(totalTTC.subtract(netApayer)));
477
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalPrepaid);
478
 
479
        final Element eTotalDue = new Element("DuePayableAmount", RAM_NS);
480
        eTotalDue.setText(this.formatAmount.format(netApayer));
481
        eSpecifiedTradeSettlementHeaderMonetarySummation.addContent(eTotalDue);
482
 
177 ilm 483
        // Total HT
484
        // <ram:LineTotalAmount>624.90</ram:LineTotalAmount>
485
        // Total HT sur leque est appliqué la TVA
486
        // <ram:TaxBasisTotalAmount>624.90</ram:TaxBasisTotalAmount>
487
        // Total des TVA
488
        // <ram:TaxTotalAmount currencyID="EUR">46.25</ram:TaxTotalAmount>
489
        // Total TTC
490
        // <ram:GrandTotalAmount>671.15</ram:GrandTotalAmount>
491
        // Montant déjà payé
492
        // <ram:TotalPrepaidAmount>201.00</ram:TotalPrepaidAmount>
493
        // Reste à payer
494
        // <ram:DuePayableAmount>470.15</ram:DuePayableAmount>
495
 
496
        eApplicableHeaderTradeSettlement.addContent(eSpecifiedTradeSettlementHeaderMonetarySummation);
497
 
498
        eSupplyChainTradeTransaction.addContent(eApplicableHeaderTradeSettlement);
499
 
500
    }
501
 
180 ilm 502
    private void addBuyerInfo(final Element eApplicableHeaderTradeAgreement, final SQLRowAccessor rowFacture) {
503
 
504
        SQLRowAccessor client = rowFacture.getForeign("ID_CLIENT");
505
        SQLRowAccessor clientGestion = client;
506
        if (this.useCommonClient) {
507
            client = client.getForeign("ID_CLIENT");
508
        }
509
        final SQLRowAccessor adr;
510
        if (!rowFacture.isForeignEmpty("ID_ADRESSE")) {
511
            adr = rowFacture.getForeign("ID_ADRESSE");
512
        } else if (!clientGestion.isForeignEmpty("ID_ADRESSE_F")) {
513
            adr = clientGestion.getForeign("ID_ADRESSE_F");
514
        } else {
515
            adr = client.getForeign("ID_ADRESSE");
516
        }
517
 
177 ilm 518
        // Acheteur
180 ilm 519
        String buyerName = client.getString("NOM");
520
        String buyerSIRET = client.getString("SIRET");
521
        String buyerVAT = client.getString("NUMERO_TVA");
522
        String buyerContactName = client.getString("RESPONSABLE");
523
        String buyerPhone = client.getString("TEL");
524
        String buyerEmail = client.getString("MAIL");
525
        String buyerAddrL1 = adr.getString("RUE");
177 ilm 526
        String buyerAddrL2 = "";
527
        String buyerAddrL3 = "";
180 ilm 528
        String buyerPostalCode = adr.getString("CODE_POSTAL");
529
        String buyerCity = adr.getString("VILLE");
530
        String buyerCountryCode = resolveCountryCode(adr.getString("PAYS"));
177 ilm 531
 
532
        final Element eBuyerTradeParty = new Element("BuyerTradeParty", RAM_NS);
533
        this.addValue(eBuyerTradeParty, new Element("Name", RAM_NS), buyerName);
534
 
535
        final Element eSpecifiedLegalOrganization = new Element("SpecifiedLegalOrganization", RAM_NS);
536
        Element eSpecifiedLegalOrganizationId = new Element("ID", RAM_NS);
537
        eSpecifiedLegalOrganizationId.setAttribute("schemeID", "0002");
538
        eSpecifiedLegalOrganizationId.setText(buyerSIRET);
539
        eSpecifiedLegalOrganization.addContent(eSpecifiedLegalOrganizationId);
540
        eBuyerTradeParty.addContent(eSpecifiedLegalOrganization);
541
        // Contact
542
        final Element eDefinedTradeContact = new Element("DefinedTradeContact", RAM_NS);
543
        addValue(eDefinedTradeContact, new Element("PersonName", RAM_NS), buyerContactName);
544
        final Element eTelephoneUniversalCommunication = new Element("TelephoneUniversalCommunication", RAM_NS);
545
        addValue(eTelephoneUniversalCommunication, new Element("CompleteNumber", RAM_NS), buyerPhone);
546
        eDefinedTradeContact.addContent(eTelephoneUniversalCommunication);
547
        final Element eEmailURIUniversalCommunication = new Element("EmailURIUniversalCommunication", RAM_NS);
548
        final Element eURIID = new Element("URIID", RAM_NS);
549
        eURIID.setAttribute("schemeID", "SMTP");
550
        eURIID.setText(buyerEmail);
551
        eEmailURIUniversalCommunication.addContent(eURIID);
552
        eDefinedTradeContact.addContent(eEmailURIUniversalCommunication);
553
        eBuyerTradeParty.addContent(eDefinedTradeContact);
554
        // Adresse postale
555
        final Element ePostalTradeAddress = new Element("PostalTradeAddress", RAM_NS);
180 ilm 556
        addValue(ePostalTradeAddress, new Element("PostcodeCode", RAM_NS), buyerPostalCode);
557
        addValue(ePostalTradeAddress, new Element("LineOne", RAM_NS), buyerAddrL1);
177 ilm 558
        if (buyerAddrL2 != null && !buyerAddrL2.trim().isEmpty()) {
180 ilm 559
            addValue(ePostalTradeAddress, new Element("LineTwo", RAM_NS), buyerAddrL2);
177 ilm 560
        }
561
        if (buyerAddrL3 != null && !buyerAddrL3.trim().isEmpty()) {
180 ilm 562
            addValue(ePostalTradeAddress, new Element("LineThree", RAM_NS), buyerAddrL3);
177 ilm 563
        }
180 ilm 564
        addValue(ePostalTradeAddress, new Element("CityName", RAM_NS), buyerCity);
565
        addValue(ePostalTradeAddress, new Element("CountryID", RAM_NS), buyerCountryCode);
177 ilm 566
 
567
        eBuyerTradeParty.addContent(ePostalTradeAddress);
568
 
180 ilm 569
        if (buyerVAT != null && buyerVAT.trim().length() > 0) {
570
            // TVA
571
            final Element eSpecifiedTaxRegistration = new Element("SpecifiedTaxRegistration", RAM_NS);
572
            final Element eSpecifiedTaxRegistrationId = new Element("ID", RAM_NS);
573
            eSpecifiedTaxRegistrationId.setAttribute("schemeID", "VA");
574
            eSpecifiedTaxRegistrationId.setText(buyerVAT);
575
            eSpecifiedTaxRegistration.addContent(eSpecifiedTaxRegistrationId);
576
            eBuyerTradeParty.addContent(eSpecifiedTaxRegistration);
577
        }
177 ilm 578
        eApplicableHeaderTradeAgreement.addContent(eBuyerTradeParty);
579
    }
580
 
180 ilm 581
    private void addSupplierInfo(final Element eApplicableHeaderTradeAgreement, SQLRowAccessor rowSociete) {
582
        String supplierName = rowSociete.getString("NOM");
583
        String supplierSIRET = rowSociete.getString("NUM_SIRET");
584
        String supplierContactName = "";
585
        String supplierContactPhone = rowSociete.getString("NUM_TEL");
586
        String supplierContactEmail = rowSociete.getString("MAIL");
587
        SQLRowAccessor adr = rowSociete.getForeign("ID_ADRESSE_COMMON");
588
        String supplierAddrL1 = adr.getString("RUE");
177 ilm 589
        String supplierAddrL2 = "";
590
        String supplierAddrL3 = "";
180 ilm 591
        String supplierAddrPostalCode = adr.getString("CODE_POSTAL");
592
        String supplierAddrCityName = adr.getString("VILLE");
593
        String supplierAddrCountryID = resolveCountryCode(adr.getString("PAYS"));
594
        String supplierNumTVA = rowSociete.getString("NUM_NII");
177 ilm 595
        // Vendeur
596
        final Element eSellerTradeParty = new Element("SellerTradeParty", RAM_NS);
597
        addValue(eSellerTradeParty, new Element("Name", RAM_NS), supplierName);
598
 
599
        final Element eSpecifiedLegalOrganization = new Element("SpecifiedLegalOrganization", RAM_NS);
600
        final Element eID = new Element("ID", RAM_NS);
601
        eID.setAttribute("schemeID", "0002");
602
        eID.setText(supplierSIRET);
603
        eSpecifiedLegalOrganization.addContent(eID);
604
        eSellerTradeParty.addContent(eSpecifiedLegalOrganization);
605
 
606
        final Element eDefinedTradeContact = new Element("DefinedTradeContact", RAM_NS);
607
        final Element ePersonName = new Element("PersonName", RAM_NS);
608
        ePersonName.setText(supplierContactName);
609
        eDefinedTradeContact.addContent(ePersonName);
610
 
611
        final Element eTelephoneUniversalCommunication = new Element("TelephoneUniversalCommunication", RAM_NS);
612
        final Element eCompleteNumber = new Element("CompleteNumber", RAM_NS);
613
        eCompleteNumber.setText(supplierContactPhone);
614
        eTelephoneUniversalCommunication.addContent(eCompleteNumber);
615
        eDefinedTradeContact.addContent(eTelephoneUniversalCommunication);
616
 
617
        final Element eEmailURIUniversalCommunication = new Element("EmailURIUniversalCommunication", RAM_NS);
618
        final Element eURIID = new Element("URIID", RAM_NS);
619
        eURIID.setAttribute("schemeID", "SMTP");
620
        eURIID.setText(supplierContactEmail);
621
        eEmailURIUniversalCommunication.addContent(eURIID);
622
        eDefinedTradeContact.addContent(eEmailURIUniversalCommunication);
623
        eSellerTradeParty.addContent(eDefinedTradeContact);
624
 
625
        final Element ePostalTradeAddress = new Element("PostalTradeAddress", RAM_NS);
180 ilm 626
        addValue(ePostalTradeAddress, new Element("PostcodeCode", RAM_NS), supplierAddrPostalCode);
177 ilm 627
        addValue(ePostalTradeAddress, new Element("LineOne", RAM_NS), supplierAddrL1);
628
        if (supplierAddrL2 != null && !supplierAddrL2.trim().isEmpty()) {
629
            addValue(ePostalTradeAddress, new Element("LineTwo", RAM_NS), supplierAddrL2);
630
        }
631
        if (supplierAddrL3 != null && !supplierAddrL3.trim().isEmpty()) {
632
            addValue(ePostalTradeAddress, new Element("LineThree", RAM_NS), supplierAddrL3);
633
        }
634
        addValue(ePostalTradeAddress, new Element("CityName", RAM_NS), supplierAddrCityName);
635
        addValue(ePostalTradeAddress, new Element("CountryID", RAM_NS), supplierAddrCountryID);
636
 
637
        eSellerTradeParty.addContent(ePostalTradeAddress);
638
 
639
        final Element eSpecifiedTaxRegistration = new Element("SpecifiedTaxRegistration", RAM_NS);
640
        final Element eSpecifiedTaxRegistrationID = new Element("ID", RAM_NS);
641
        eSpecifiedTaxRegistrationID.setAttribute("schemeID", "VA");
642
        eSpecifiedTaxRegistrationID.setText(supplierNumTVA);
643
        eSpecifiedTaxRegistration.addContent(eSpecifiedTaxRegistrationID);
644
        eSellerTradeParty.addContent(eSpecifiedTaxRegistration);
645
 
646
        eApplicableHeaderTradeAgreement.addContent(eSellerTradeParty);
647
    }
648
 
649
    private void addIncludedNote(String content, String code, Element ed) {
650
        final Element e = new Element("IncludedNote", RAM_NS);
651
        final Element eContent = new Element("Content", RAM_NS);
652
        eContent.setText(content);
653
        e.addContent(eContent);
654
        final Element eCode = new Element("SubjectCode", RAM_NS);
655
        eCode.setText(code);
656
        e.addContent(eCode);
657
        ed.addContent(e);
658
    }
659
 
660
    private void addDateTime(Date date, Element eTime) {
661
        final Element e = new Element("DateTimeString", UDT_NS);
662
        // From the doc : Only value "102" ...
663
        e.setAttribute("format", "102");
664
        SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
665
        e.setText(s.format(date));
666
        eTime.addContent(e);
667
    }
668
 
669
    boolean checkEAN13(String code) {
670
        if (code == null || code.length() != 13) {
671
            return false;
672
        }
182 ilm 673
        try {
674
            int checkdigit = 0;
675
            for (int i = 1; i < 12; i += 2) {
676
                checkdigit += Integer.valueOf(code.substring(i, i + 1));
677
            }
678
            checkdigit *= 3;
679
            for (int i = 0; i < 11; i += 2) {
680
                checkdigit += Integer.valueOf(code.substring(i, i + 1));
681
            }
682
            checkdigit %= 10;
683
            if (checkdigit != 0) {
684
                checkdigit = 10 - checkdigit;
685
            }
686
            return Integer.valueOf(code.substring(12, 13)).intValue() == checkdigit;
687
        } catch (Exception e) {
688
            // if not digits, parse error
689
            return false;
177 ilm 690
        }
691
    }
180 ilm 692
 
693
    private String resolveCountryCode(String pays) {
694
        if (pays == null || pays.trim().length() == 0) {
695
            return "FR";
696
        } else if (pays.toLowerCase().equals("france")) {
697
            return "FR";
698
        } else if (pays.toLowerCase().equals("fr")) {
699
            return "FR";
700
        } else if (pays.toLowerCase().equals("polska")) {
701
            return "PL";
702
        } else if (pays.toLowerCase().equals("pologne")) {
703
            return "PL";
704
        } else if (pays.toLowerCase().equals("pl")) {
705
            return "PL";
706
        } else if (pays.toLowerCase().equals("allemagne")) {
707
            return "DE";
708
        } else if (pays.toLowerCase().equals("de")) {
709
            return "DE";
710
        } else if (pays.toLowerCase().equals("deutschland")) {
711
            return "DE";
712
        } else if (pays.toLowerCase().equals("italie")) {
713
            return "IT";
714
        } else if (pays.toLowerCase().equals("italy")) {
715
            return "IT";
716
        } else if (pays.toLowerCase().equals("italia")) {
717
            return "IT";
718
        } else if (pays.toLowerCase().equals("it")) {
719
            return "IT";
720
        } else if (pays.toLowerCase().equals("espagne")) {
721
            return "SP";
722
        } else if (pays.toLowerCase().equals("spain")) {
723
            return "SP";
724
        } else if (pays.toLowerCase().equals("sp")) {
725
            return "SP";
726
        } else if (pays.toLowerCase().equals("luxembourg")) {
727
            return "LU";
728
        } else if (pays.toLowerCase().equals("lu")) {
729
            return "LU";
730
        } else if (pays.toLowerCase().equals("portugal")) {
731
            return "PT";
732
        } else if (pays.toLowerCase().equals("pt")) {
733
            return "PT";
734
        } else if (pays.toLowerCase().equals("belgique")) {
735
            return "BE";
736
        } else if (pays.toLowerCase().equals("belgium")) {
737
            return "BE";
738
        } else if (pays.toLowerCase().equals("be")) {
739
            return "BE";
740
        } else {
741
            return "";
742
        }
743
    }
177 ilm 744
}