OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 156 | 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 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */
 
 package org.openconcerto.erp.generationEcritures;

import org.openconcerto.erp.core.common.element.BanqueSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.ComptePCESQLElement;
import org.openconcerto.erp.core.finance.accounting.element.JournalSQLElement;
import org.openconcerto.erp.core.finance.accounting.element.MouvementSQLElement;
import org.openconcerto.erp.core.finance.payment.element.ModeDeReglementSQLElement;
import org.openconcerto.erp.core.finance.payment.element.TypeReglementSQLElement;
import org.openconcerto.erp.core.sales.invoice.element.SaisieVenteFactureSQLElement;
import org.openconcerto.erp.model.PrixTTC;
import org.openconcerto.sql.model.SQLRow;
import org.openconcerto.sql.model.SQLRowValues;
import org.openconcerto.sql.model.SQLTable;
import org.openconcerto.utils.ExceptionHandler;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// FIXME mettre toute les generations dans des threads à part
public final class GenerationMvtReglementFactureFournisseur extends GenerationEcritures implements Runnable {

    private int idfacture;

    // Journal Caisse
    private static final Integer journalCaisse = Integer.valueOf(JournalSQLElement.CAISSES);

    private static final SQLTable tablePrefCompte = base.getTable("PREFS_COMPTE");
    private static final SQLTable tableMouvement = base.getTable("MOUVEMENT");
    private static final SQLRow rowPrefsCompte = tablePrefCompte.getRow(2);
    private int idPere = 1; // Id du mouvement pere

    public GenerationMvtReglementFactureFournisseur(int idFacture, int idMvt) {
        this.idfacture = idFacture;
        this.idPere = idMvt;
        new Thread(GenerationMvtReglementFactureFournisseur.this).start();
    }

    private void genereReglement() throws Exception {

        System.out.println("Génération des ecritures du reglement du mouvement " + this.idMvt);

        SQLRow saisieRow = base.getTable("FACTURE_FOURNISSEUR").getRow(this.idfacture);
        SQLRow modeRegRow = base.getTable("MODE_REGLEMENT").getRow(saisieRow.getInt("ID_MODE_REGLEMENT"));
        SQLRow typeRegRow = base.getTable("TYPE_REGLEMENT").getRow(modeRegRow.getInt("ID_TYPE_REGLEMENT"));

        System.out.println("Mode de reglement " + saisieRow.getInt("ID_MODE_REGLEMENT"));

        // PrixTTC prixTTC = new PrixTTC(((Long) saisieRow.getObject("MONTANT_TTC")).longValue());

        PrixTTC prixTTC;
        // int idAvoir = saisieRow.getInt("ID_AVOIR_FOURNISSEUR");
        // if (idAvoir > 1) {
        // SQLRow avoirRow = base.getTable("AVOIR_FOURNISSEUR").getRow(idAvoir);
        // long l = ((Number) avoirRow.getObject("MONTANT_TTC")).longValue();
        // prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue() - l);
        // } else {
        prixTTC = new PrixTTC(((Long) saisieRow.getObject("NET_A_PAYER")).longValue());
        // }

        this.date = (Date) saisieRow.getObject("DATE");
        SQLRow rowFournisseur = base.getTable("FOURNISSEUR").getRow(saisieRow.getInt("ID_FOURNISSEUR"));
        this.nom = "Règlement Achat : " + rowFournisseur.getString("NOM") + " Facture : " + saisieRow.getObject("NUMERO").toString() + " (" + typeRegRow.getString("NOM") + ")";

        // si paiement comptant
        if ((modeRegRow.getInt("AJOURS") == 0) && (modeRegRow.getInt("LENJOUR") == 0) && !typeRegRow.getBoolean("ECHEANCE")) {

            System.out.println("Règlement Comptant");
            // test Cheque
            if (typeRegRow.getID() == 2) {
                Calendar c = modeRegRow.getDate("DATE_DEPOT");
                if (c != null) {
                    paiementCheque(c.getTime());
                } else {
                    paiementCheque(this.date);
                }
            } else {

                this.idMvt = this.idPere;

                // iniatilisation des valeurs de la map
                this.putValue("DATE", new java.sql.Date(this.date.getTime()));
                this.putValue("NOM", this.nom);
                this.putValue("ID_MOUVEMENT", Integer.valueOf(this.idMvt));

                if (typeRegRow.getID() == 4) {
                    this.putValue("ID_JOURNAL", GenerationMvtReglementFactureFournisseur.journalCaisse);
                } else {

                    fillJournalBanqueFromRow(modeRegRow);
                }

                // compte Fournisseurs
                int compteFourn = rowFournisseur.getInt("ID_COMPTE_PCE");
                if (compteFourn <= 1) {
                    compteFourn = rowPrefsCompte.getInt("ID_COMPTE_PCE_FOURNISSEUR");
                    if (compteFourn <= 1) {
                        compteFourn = ComptePCESQLElement.getIdComptePceDefault("Fournisseurs");
                    }
                }

                this.putValue("ID_COMPTE_PCE", Integer.valueOf(compteFourn));
                this.putValue("DEBIT", Long.valueOf(prixTTC.getLongValue()));
                this.putValue("CREDIT", Long.valueOf(0));
                ajoutEcriture();

                // compte de reglement, caisse, CB, ...
                if (typeRegRow.getID() == TypeReglementSQLElement.ESPECE) {
                    int idCompteRegl = typeRegRow.getInt("ID_COMPTE_PCE_FOURN");
                    if (idCompteRegl <= 1) {
                        idCompteRegl = ComptePCESQLElement.getIdComptePceDefault("AchatEspece");
                    }

                    this.putValue("ID_COMPTE_PCE", Integer.valueOf(idCompteRegl));
                } else {
                    fillCompteBanqueFromRow(modeRegRow, "AchatCB", true);
                }
                this.putValue("DEBIT", Long.valueOf(0));
                this.putValue("CREDIT", Long.valueOf(prixTTC.getLongValue()));
                ajoutEcriture();
            }
            setDateReglement(saisieRow, this.date);
        } else {

            Date dateEch = ModeDeReglementSQLElement.calculDate(modeRegRow.getInt("AJOURS"), modeRegRow.getInt("LENJOUR"), this.date);
            DateFormat dateFormat = new SimpleDateFormat();
            System.out.println("Date d'échéance " + dateFormat.format(dateEch));
            // System.out.println("Echeance" + dateEch);

            // Cheque
            if (typeRegRow.getID() == 2) {

                // Ajout dans cheque fournisseur
                paiementCheque(dateEch);
            } else {

                // Ajout dans echeance
                Map<String, Object> mEcheance = new HashMap<String, Object>();

                SQLTable echeanceTable = base.getTable("ECHEANCE_FOURNISSEUR");
                SQLRow rowMvtPere = tableMouvement.getRow(this.idPere);
                this.idMvt = getNewMouvement("ECHEANCE_FOURNISSEUR", 1, this.idPere, rowMvtPere.getInt("ID_PIECE"));

                mEcheance.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));
                mEcheance.put("DATE", new java.sql.Date(dateEch.getTime()));
                mEcheance.put("MONTANT", Long.valueOf(prixTTC.getLongValue()));
                mEcheance.put("ID_FOURNISSEUR", saisieRow.getForeignID("ID_FOURNISSEUR"));
                mEcheance.put("ID_FACTURE_FOURNISSEUR", saisieRow.getID());
                if (saisieRow.getTable().contains("ID_AFFAIRE") && echeanceTable.contains("ID_AFFAIRE")) {
                    if (!saisieRow.isForeignEmpty("ID_AFFAIRE")) {
                        mEcheance.put("ID_AFFAIRE", saisieRow.getForeignID("ID_AFFAIRE"));
                    }
                }

                SQLRowValues valEcheance = new SQLRowValues(echeanceTable, mEcheance);

                if (valEcheance.getInvalid() == null) {
                    // ajout de l'ecriture
                    SQLRow row = valEcheance.insert();
                    SQLRowValues rowVals = new SQLRowValues(tableMouvement);
                    rowVals.put("IDSOURCE", row.getID());
                    rowVals.update(this.idMvt);
                }

            }
        }
    }

    /**
     * Reglement par cheque. Crée un cheque fournisseur à décaisser.
     * 
     * @param dateEch date d'echeance d'encaissement du cheque
     * @throws SQLException
     */
    private void paiementCheque(Date dateEch) throws SQLException {

        SQLRow saisieRow = base.getTable("FACTURE_FOURNISSEUR").getRow(this.idfacture);
        // PrixTTC prixTTC = new PrixTTC(((Long) saisieRow.getObject("MONTANT_TTC")).longValue());

        PrixTTC prixTTC;
        // int idAvoir = saisieRow.getInt("ID_AVOIR_FOURNISSEUR");
        // if (idAvoir > 1) {
        // SQLRow avoirRow = base.getTable("AVOIR_FOURNISSEUR").getRow(idAvoir);
        // long l = ((Number) avoirRow.getObject("MONTANT_TTC")).longValue();
        // prixTTC = new PrixTTC(((Long) saisieRow.getObject("T_TTC")).longValue() - l);
        // } else {
        prixTTC = new PrixTTC(((Long) saisieRow.getObject("NET_A_PAYER")).longValue());
        // }

        // Ajout dans cheque fournisseur
        Map<String, Object> mEncaisse = new HashMap<String, Object>();
        mEncaisse.put("ID_FOURNISSEUR", Integer.valueOf(saisieRow.getInt("ID_FOURNISSEUR")));
        mEncaisse.put("DATE_ACHAT", new java.sql.Date(this.date.getTime()));
        mEncaisse.put("DATE_MIN_DECAISSE", new java.sql.Date(dateEch.getTime()));
        mEncaisse.put("MONTANT", Long.valueOf(prixTTC.getLongValue()));
        if (!saisieRow.isForeignEmpty("ID_MODE_REGLEMENT")) {
            SQLRow rowModeRegl = saisieRow.getForeignRow("ID_MODE_REGLEMENT");
            mEncaisse.put("ID_" + BanqueSQLElement.TABLENAME, rowModeRegl.getInt("ID_" + BanqueSQLElement.TABLENAME));
        }

        SQLRow rowMvtPere = tableMouvement.getRow(this.idPere);
        this.idMvt = getNewMouvement("CHEQUE_FOURNISSEUR", 1, this.idPere, rowMvtPere.getInt("ID_PIECE"));

        mEncaisse.put("ID_MOUVEMENT", Integer.valueOf(this.idMvt));

        SQLTable chqFournTable = base.getTable("CHEQUE_FOURNISSEUR");

        SQLRowValues valDecaisse = new SQLRowValues(chqFournTable, mEncaisse);

        if (valDecaisse.getInvalid() == null) {

            // ajout de l'ecriture
            SQLRow row = valDecaisse.insert();

            SQLRowValues rowVals = new SQLRowValues(tableMouvement);
            rowVals.put("IDSOURCE", row.getID());
            rowVals.update(this.idMvt);
        }

    }

    private void setDateReglement(SQLRow source, Date d) throws SQLException {

        SQLRowValues rowValsUpdateVF = source.createEmptyUpdateRow();
        rowValsUpdateVF.put("DATE_REGLEMENT", d);
        rowValsUpdateVF.update();

    }

    public void run() {
        try {
            genereReglement();
        } catch (Exception e) {
            ExceptionHandler.handle("Erreur pendant la générations des écritures comptables", e);
            e.printStackTrace();
        }
    }
}