OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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