OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 174 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011-2019 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.erp.core.sales.pos.element;

import org.openconcerto.erp.config.ComptaPropsConfiguration;
import org.openconcerto.erp.core.common.element.ComptaSQLConfElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.finance.tax.model.TaxeCache;
import org.openconcerto.erp.core.sales.pos.TicketSheetXML;
import org.openconcerto.erp.core.sales.pos.model.Article;
import org.openconcerto.erp.core.sales.pos.model.Categorie;
import org.openconcerto.erp.core.sales.pos.model.Paiement;
import org.openconcerto.erp.core.sales.pos.model.ReceiptCode;
import org.openconcerto.erp.core.sales.pos.model.Ticket;
import org.openconcerto.sql.Configuration;
import org.openconcerto.sql.element.SQLComponent;
import org.openconcerto.sql.element.SQLElement;
import org.openconcerto.sql.element.SQLElementDirectory;
import org.openconcerto.sql.element.UISQLComponent;
import org.openconcerto.sql.model.SQLBase;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowListRSH;
import org.openconcerto.sql.model.SQLSelect;
import org.openconcerto.sql.utils.PartialUniqueTrigger;
import org.openconcerto.sql.view.list.IListeAction.IListeEvent;
import org.openconcerto.sql.view.list.action.SQLRowValuesAction.PredicateRowAction;
import org.openconcerto.utils.DecimalUtils;
import org.openconcerto.utils.ExceptionHandler;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JTextField;

public class TicketCaisseSQLElement extends ComptaSQLConfElement {

    static public final String UNARCHIVED_WHERE = SQLBase.quoteIdentifier("ARCHIVE") + " = " + 0;
    static public final String DATE_WHERE = UNARCHIVED_WHERE + " and " + SQLBase.quoteIdentifier("FILE_HASH") + " is not null";

    // needed until H2 databases are upgraded to use JS code
    static public final class UniqueNumber_PartialUniqueTrigger extends PartialUniqueTrigger {
        public UniqueNumber_PartialUniqueTrigger() {
            super(Arrays.asList("NUMERO"), UNARCHIVED_WHERE);
        }
    }

    // needed until H2 databases are upgraded to use JS code
    static public final class UniqueDate_PartialUniqueTrigger extends PartialUniqueTrigger {
        public UniqueDate_PartialUniqueTrigger() {
            super(Arrays.asList("ID_CAISSE", "DATE"), DATE_WHERE);
        }
    }

    public TicketCaisseSQLElement() {
        super("TICKET_CAISSE", "un ticket de caisse", "tickets de caisses");

        PredicateRowAction action = new PredicateRowAction(true, "ticket.document.generate", (le) -> {
            final TicketSheetXML bSheet = new TicketSheetXML(createTicket(le.getSelectedRow().asRow()), ComptaPropsConfiguration.getInstanceCompta());
            try {
                bSheet.createDocument();
                bSheet.showPrintAndExport(true, false, false, Collections.emptyList());
            } catch (Exception originalExn) {
                ExceptionHandler.handle("Erreur lors de la création de la facture", originalExn);
            }
        });

        action.setPredicate(IListeEvent.getSingleSelectionPredicate());
        getRowValuesActions().add(action);
    }

    protected List<String> getListFields() {
        final List<String> l = new ArrayList<String>();
        l.add("NUMERO");
        l.add("DATE");
        l.add("ID_CAISSE");
        l.add("TOTAL_HT");
        l.add("TOTAL_TTC");
        return l;
    }

    protected List<String> getComboFields() {
        final List<String> l = new ArrayList<String>();
        l.add("NOM");
        return l;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.openconcerto.devis.SQLElement#getComponent()
     */
    public SQLComponent createComponent() {
        return new UISQLComponent(this) {
            public void addViews() {
                this.addRequiredSQLObject(new JTextField(), "NOM", "right");
            }
        };
    }

    public Ticket createTicket(SQLRow row) {
        // TODO merger ce code avec CaissepPanel.loadArticles si possible
        final Ticket t;
        try {
            t = new Ticket(new ReceiptCode(row.getString("NUMERO")), row.getDate("DATE"), row.getString("FILE_HASH_PREVIOUS"));
        } catch (ParseException e) {
            throw new IllegalStateException("Couldn't parse " + row, e);
        }

        final SQLElementDirectory directory = Configuration.getInstance().getDirectory();
        SQLElement eltEncaisser = directory.getElement("ENCAISSER_MONTANT");
        List<SQLRow> l = row.getReferentRows(eltEncaisser.getTable());
        for (SQLRow row2 : l) {
            long montant = row2.getLong("MONTANT");
            SQLRow rowMode = row2.getForeign("ID_MODE_REGLEMENT");
            int type = Paiement.CB;
            if (rowMode.getInt("ID_TYPE_REGLEMENT") == TypeReglementSQLElement.CB) {
                type = Paiement.CB;
            } else {
                if (rowMode.getInt("ID_TYPE_REGLEMENT") == TypeReglementSQLElement.CHEQUE) {
                    type = Paiement.CHEQUE;
                } else {
                    if (rowMode.getInt("ID_TYPE_REGLEMENT") == TypeReglementSQLElement.ESPECE) {
                        type = Paiement.ESPECES;
                    }
                }
            }
            Paiement p = new Paiement(type);
            p.setMontantInCents((int) montant);
            t.addPaiement(p);
        }

        SQLElement eltArticle = directory.getElement("SAISIE_VENTE_FACTURE_ELEMENT");

        final SQLSelect selUniteVente = new SQLSelect();
        selUniteVente.addSelectStar(directory.getElement("UNITE_VENTE").getTable());
        final Map<Integer, String> mapUniteVenteName = new HashMap<>();
        for (SQLRow rowUniteVente : SQLRowListRSH.execute(selUniteVente)) {
            mapUniteVenteName.put(rowUniteVente.getID(), rowUniteVente.getString("CODE"));
        }

        List<SQLRow> l2 = row.getReferentRows(eltArticle.getTable());
        Categorie c = new Categorie("");
        for (SQLRow row2 : l2) {
            Article a = new Article(c, row2.getString("NOM"), row2.getInt("ID_ARTICLE"));
            if (row2.getInt("ID_UNITE_VENTE") != 2) {
                a.setSalesUnit(mapUniteVenteName.get(row2.getInt("ID_UNITE_VENTE")));
            }
            BigDecimal ht = (BigDecimal) row2.getObject("PV_HT");
            a.setPriceWithoutTax(ht);

            BigDecimal percentRemise = row2.getBigDecimal("POURCENT_REMISE");
            if (percentRemise != null) {
                a.setDiscountPct(percentRemise.movePointLeft(2));
            }

            int idTaxe = row2.getInt("ID_TAXE");
            float tva = TaxeCache.getCache().getTauxFromId(idTaxe);
            a.setPriceWithTax(ht.multiply(BigDecimal.valueOf(1.0 + (tva / 100.0D)), DecimalUtils.HIGH_PRECISION));
            a.setIdTaxe(idTaxe);
            t.addArticle(a);
            if (a.getSalesUnit() == null) {
                t.setArticleCount(a, new BigDecimal(row2.getInt("QTE")));
            } else {
                t.setArticleCount(a, row2.getBigDecimal("QTE_UNITAIRE"));
            }
        }

        return t;
    }

    @Override
    protected String createCode() {
        return createCodeOfPackage() + ".ticket";
    }
}