Search in sources :

Example 1 with MCurrency

use of org.compiere.model.MCurrency in project lar_361 by comitsrl.

the class InvoiceGenerate method completeInvoice.

// createLine
/**
 * 	Complete Invoice
 */
private void completeInvoice() {
    if (m_invoice != null) {
        // @emmie custom
        m_invoice.set_ValueOfColumn("C_POS_ID", p_C_POS_ID);
        // @emmie custom
        MOrder order = new MOrder(getCtx(), m_invoice.getC_Order_ID(), get_TrxName());
        if (order != null) {
            m_invoice.setPaymentRule(order.getPaymentRule());
            m_invoice.setC_PaymentTerm_ID(order.getC_PaymentTerm_ID());
            m_invoice.saveEx();
            // refresh from DB
            m_invoice.load(m_invoice.get_TrxName());
            // copy payment schedule from order if invoice doesn't have a current payment schedule
            MOrderPaySchedule[] opss = MOrderPaySchedule.getOrderPaySchedule(getCtx(), order.getC_Order_ID(), 0, get_TrxName());
            MInvoicePaySchedule[] ipss = MInvoicePaySchedule.getInvoicePaySchedule(getCtx(), m_invoice.getC_Invoice_ID(), 0, get_TrxName());
            if (ipss.length == 0 && opss.length > 0) {
                BigDecimal ogt = order.getGrandTotal();
                BigDecimal igt = m_invoice.getGrandTotal();
                BigDecimal percent = Env.ONE;
                if (ogt.compareTo(igt) != 0)
                    percent = igt.divide(ogt, 10, BigDecimal.ROUND_HALF_UP);
                MCurrency cur = MCurrency.get(order.getCtx(), order.getC_Currency_ID());
                int scale = cur.getStdPrecision();
                for (MOrderPaySchedule ops : opss) {
                    MInvoicePaySchedule ips = new MInvoicePaySchedule(getCtx(), 0, get_TrxName());
                    PO.copyValues(ops, ips);
                    if (percent != Env.ONE) {
                        BigDecimal propDueAmt = ops.getDueAmt().multiply(percent);
                        if (propDueAmt.scale() > scale)
                            propDueAmt = propDueAmt.setScale(scale, BigDecimal.ROUND_HALF_UP);
                        ips.setDueAmt(propDueAmt);
                    }
                    ips.setC_Invoice_ID(m_invoice.getC_Invoice_ID());
                    ips.setAD_Org_ID(ops.getAD_Org_ID());
                    ips.setProcessing(ops.isProcessing());
                    ips.setIsActive(ops.isActive());
                    ips.saveEx();
                }
                m_invoice.validatePaySchedule();
                m_invoice.saveEx();
            }
        }
        if (!m_invoice.processIt(p_docAction)) {
            log.warning("completeInvoice - failed: " + m_invoice);
            // Elaine 2008/11/25
            addLog("completeInvoice - failed: " + m_invoice);
            throw new IllegalStateException("Invoice Process Failed: " + m_invoice + " - " + m_invoice.getProcessMsg());
        } else // @emmie custom - impresion fiscal en caso de que la operación sea CO (completar)
        // y la factura sea fiscal
        {
            m_invoice.saveEx();
            if (p_docAction.equals(MInvoice.DOCACTION_Complete) && LAR_Utils.isFiscalDocType(m_invoice.getC_DocType_ID())) {
                final InvoiceFiscalDocumentPrintManager manager = new InvoiceFiscalDocumentPrintManager(m_invoice);
                manager.print();
            }
        }
        // @emmie custom
        addLog(m_invoice.getC_Invoice_ID(), m_invoice.getDateInvoiced(), null, m_invoice.getDocumentNo());
        m_created++;
    }
    m_invoice = null;
    m_ship = null;
    m_line = 0;
}
Also used : MOrder(org.compiere.model.MOrder) MCurrency(org.compiere.model.MCurrency) InvoiceFiscalDocumentPrintManager(ar.com.ergio.print.fiscal.view.InvoiceFiscalDocumentPrintManager) MOrderPaySchedule(org.compiere.model.MOrderPaySchedule) MInvoicePaySchedule(org.compiere.model.MInvoicePaySchedule) BigDecimal(java.math.BigDecimal)

Example 2 with MCurrency

use of org.compiere.model.MCurrency in project lar_361 by comitsrl.

the class WsfeV1 method createInputFile.

/**
 * @author: Horacio Alvarez
 * @descripcion: Crea el archivo de entrada para el WSFE.PY.
 * Setea los valores necesarios con el objeto MInvoice.
 */
@Override
protected void createInputFile() {
    try {
        StringBuffer line = new StringBuffer();
        // *****NRO. COMPROBANTE
        if (this.getInvoice().getNumeroComprobante() == 0) {
            this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoNumeroComprobante"));
            return;
        }
        line.append(this.getInvoice().getNumeroComprobante() + "\n");
        // *****PUNTO DE VENTA
        final MPOS pos = new MPOS(getM_ctx(), this.getInvoice().get_ValueAsInt("C_Pos_ID"), getTrxName());
        if (pos.get_ValueAsInt("PosNumber") == 0) {
            this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoPuntoDeVenta"));
            return;
        }
        line.append(pos.get_ValueAsInt("PosNumber") + "\n");
        // *****TIPO DE COMPROBANTE
        MDocType docType = new MDocType(Env.getCtx(), this.getInvoice().getC_DocTypeTarget_ID(), getTrxName());
        line.append(docType.getdocsubtypecae() + "\n");
        // *****TIPO DOC: 80 CUIT / 96 DNI
        MBPartner partner = new MBPartner(this.getM_ctx(), this.getInvoice().getC_BPartner_ID(), getTrxName());
        final X_LCO_TaxPayerType taxPayerType = new X_LCO_TaxPayerType(getM_ctx(), partner.get_ValueAsInt("LCO_TaxPayerType_ID"), getTrxName());
        if (taxPayerType.getName().equals("ConsumidorFinal")) {
            line.append("96" + "\n");
            line.append("1" + "\n");
        } else {
            line.append("80" + "\n");
            if (partner.getTaxID() == null || partner.getTaxID().equals("")) {
                this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoCUIT"));
                return;
            }
            line.append(partner.getTaxID().replaceAll("-", "") + "\n");
        }
        // *****IMPORTE TOTAL
        // line.append(this.getInvoice().getGrandTotal().toString().replace(".", "")+"\n");
        line.append(this.getInvoice().getGrandTotal().setScale(2, BigDecimal.ROUND_HALF_UP) + "\n");
        // *****IMPORTE NETO
        // line.append(this.getInvoice().getTotalLines().toString().replace(".", "")+"\n");
        line.append(this.getInvoice().getTotalLines().setScale(2, BigDecimal.ROUND_HALF_UP) + "\n");
        // *****FECHA
        if (this.getInvoice().getDateAcct() == null) {
            this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoDateAcct"));
            return;
        }
        line.append(formatTime(this.getInvoice().getDateAcct(), "yyyyMMdd") + "\n");
        // *****PRESTA SERVICIOS 0-->NO  1-->SI
        line.append(MSysConfig.getValue("LAR_PrestaServicios_FE", Env.getAD_Client_ID(Env.getCtx())) + "\n");
        // *****MONEDA
        MCurrency currency = new MCurrency(this.getM_ctx(), this.getInvoice().getC_Currency_ID(), getTrxName());
        line.append(currency.get_ValueAsString("WSFECode") + "\n");
        // *****CONVERSION
        // Se debe convertir a la moneda del comprobante desde la moneda de la compañía
        BigDecimal cotizacion = MCurrency.currencyConvert(Env.ONE, Env.getContextAsInt(this.getM_ctx(), "$C_Currency_ID"), this.getInvoice().getC_Currency_ID(), this.getInvoice().getDateInvoiced(), 0, this.getM_ctx());
        line.append(cotizacion + "\n");
        // *****IMPUESTO
        BigDecimal total_Impuesto = BigDecimal.ZERO;
        MInvoiceTax[] taxes = this.getInvoice().getTaxes(false);
        MTax tax = null;
        int size = taxes.length;
        boolean firstLineAppended = false;
        for (int i = 0; i < size; i++) {
            tax = MTax.get(this.getM_ctx(), taxes[i].getC_Tax_ID());
            if (!tax.get_ValueAsBoolean("IsPerception")) {
                total_Impuesto = total_Impuesto.add(taxes[i].getTaxAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
                taxes[i].getTaxAmt();
                taxes[i].getTaxBaseAmt();
                tax.get_ValueAsString("WSFECode");
                if (firstLineAppended) {
                    line.append(";");
                }
                line.append(tax.get_ValueAsString("WSFECode") + ":" + (getTaxBaseAmt(taxes[i].getTaxBaseAmt(), this.getInvoice().getGrandTotal(), getTaxesAmt(this.getInvoice()))).setScale(2, BigDecimal.ROUND_HALF_UP) + ":" + taxes[i].getTaxAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
                firstLineAppended = true;
            }
        }
        line.append("\n");
        // *****MONTO TOTAL DE IMPUESTOS
        line.append(total_Impuesto + "\n");
        // *****IMPUESTOS PERCEPCIONES
        BigDecimal total_Perception = BigDecimal.ZERO;
        MInvoiceTax[] taxesPerc = this.getInvoice().getTaxes(true);
        MTax taxPerc = null;
        int sizePerc = taxesPerc.length;
        boolean firstLineAppended2 = false;
        for (int i = 0; i < sizePerc; i++) {
            taxPerc = MTax.get(this.getM_ctx(), taxesPerc[i].getC_Tax_ID());
            if (taxPerc.get_ValueAsBoolean("IsPerception")) {
                total_Perception = total_Perception.add(taxesPerc[i].getTaxAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
                taxesPerc[i].getTaxAmt();
                taxesPerc[i].getTaxBaseAmt();
                taxPerc.get_ValueAsInt("WSFECode");
                if (firstLineAppended2) {
                    line.append(";");
                }
                BigDecimal alic = (taxPerc.getRate().setScale(2, BigDecimal.ROUND_HALF_UP)).negate();
                line.append(taxPerc.get_ValueAsInt("WSFECode") + ":" + (getTaxBaseAmt(taxesPerc[i].getTaxBaseAmt(), this.getInvoice().getGrandTotal(), getTaxesAmt(this.getInvoice()))).setScale(2, BigDecimal.ROUND_HALF_UP) + ":" + taxesPerc[i].getTaxAmt().setScale(2, BigDecimal.ROUND_HALF_UP) + ":" + alic);
                firstLineAppended2 = true;
            }
        }
        if (total_Perception.equals(Env.ZERO))
            line.append("0");
        line.append("\n");
        // *****MONTO TOTAL DE PERCEPCIONES
        line.append(total_Perception + "\n");
        // *****C_INVOICE_ID para seguimiento
        line.append(this.getInvoice().getC_Invoice_ID() + "\n");
        File textFile = new File(getPath() + "entrada.txt");
        FileWriter textOut;
        textOut = new FileWriter(textFile);
        textOut.write(line.toString());
        textOut.close();
    } catch (Exception ex) {
        this.setMessageError(Msg.translate(this.getM_ctx(), "caeErrorCreateInputFile"));
        log.log(Level.SEVERE, this.getMessageError(), ex);
    }
}
Also used : MDocType(org.compiere.model.MDocType) MPOS(org.compiere.model.MPOS) MCurrency(org.compiere.model.MCurrency) FileWriter(java.io.FileWriter) MBPartner(org.compiere.model.MBPartner) BigDecimal(java.math.BigDecimal) X_LCO_TaxPayerType(org.globalqss.model.X_LCO_TaxPayerType) MTax(org.compiere.model.MTax) MInvoiceTax(org.compiere.model.MInvoiceTax) File(java.io.File)

Example 3 with MCurrency

use of org.compiere.model.MCurrency in project lar_361 by comitsrl.

the class WsfexV1 method createInputFile.

@Override
protected void createInputFile() {
    try {
        StringBuffer line = new StringBuffer();
        // *****NRO. COMPROBANTE
        if (this.getInvoice().getNumeroComprobante() == 0) {
            this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoNumeroComprobante"));
            return;
        }
        line.append(this.getInvoice().getNumeroComprobante() + "\n");
        // *****PUNTO DE VENTA
        if (this.getInvoice().get_ValueAsInt("PuntoDeVenta") == 0) {
            this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoPuntoDeVenta"));
            return;
        }
        line.append(this.getInvoice().get_ValueAsInt("PuntoDeVenta") + "\n");
        // *****TIPO DE COMPROBANTE
        MDocType docType = new MDocType(Env.getCtx(), this.getInvoice().getC_DocTypeTarget_ID(), this.getTrxName());
        line.append(docType.getdocsubtypecae() + "\n");
        // *****IMPORTE TOTAL
        line.append(this.getInvoice().getGrandTotal() + "\n");
        // *****FECHA
        if (this.getInvoice().getDateAcct() == null) {
            this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoDateAcct"));
            return;
        }
        line.append(formatTime(this.getInvoice().getDateAcct(), "yyyyMMdd") + "\n");
        MClientInfo clientInfo = MClientInfo.get(this.getM_ctx(), this.getInvoice().getAD_Client_ID());
        MOrgInfo orgInfo = MOrgInfo.get(this.getM_ctx(), this.getInvoice().getAD_Org_ID());
        // *****MONEDA
        MCurrency currency = new MCurrency(this.getM_ctx(), this.getInvoice().getC_Currency_ID(), this.getTrxName());
        line.append(currency.get_ValueAsString("WSFECode") + "\n");
        // *****COTIZACION
        // Se debe convertir a la moneda del comprobante desde la moneda de la compañía
        BigDecimal cotizacion = MCurrency.currencyConvert(Env.ONE, this.getInvoice().getC_Currency_ID(), Env.getContextAsInt(this.getM_ctx(), "$C_Currency_ID"), this.getInvoice().getDateInvoiced(), 0, this.getM_ctx());
        line.append(cotizacion + "\n");
        // *****TIPO EXPORTACION
        /* 1 Exportación definitiva de Bienes - 2 Servicios - 4 Otros */
        String exportTypeFE = "";
        if (!Util.isEmpty(orgInfo.getExportTypeFE())) {
            exportTypeFE = orgInfo.getExportTypeFE();
        } else {
            if (!Util.isEmpty(clientInfo.get_ValueAsString("ExportTypeFE"))) {
                exportTypeFE = clientInfo.get_ValueAsString("ExportTypeFE");
            } else {
                this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoTipoExportacion"));
                return;
            }
        }
        line.append(exportTypeFE + "\n");
        // *****PERMISO DE EMBARQUE
        String shipmentPermitFE = "";
        // Si el tipo de exportación es "Exportación definitiva de Bienes" y el tipo de comprobante es Factura, entonces tomamos el valor de la configuración de Organización / Compañía
        if ((exportTypeFE.compareTo(MClientInfo.EXPORTTYPEFE_ExportaciónDefinitivaDeBienes) == 0) && (docType.getdocsubtypecae().compareTo(MDocType.DOCSUBTYPECAE_FacturaDeExportaciónE) == 0)) {
            /* Veo si la configuración es a nivel de organización. */
            if (!Util.isEmpty(orgInfo.getExportTypeFE())) {
                shipmentPermitFE = (orgInfo.get_ValueAsBoolean("isShipmentPermitFE") ? "S" : "N");
            } else {
                shipmentPermitFE = (clientInfo.get_ValueAsBoolean("isShipmentPermitFE") ? "S" : "N");
            }
        }
        line.append(shipmentPermitFE + "\n");
        // *****PAIS DESTINO
        String paisDestino;
        if (this.getInvoice().getC_BPartner_Location() != null) {
            MLocation location = new MLocation(this.getM_ctx(), this.getInvoice().getC_BPartner_Location_ID(), this.getInvoice().get_TableName());
            paisDestino = location.getCountry().get_ValueAsString("CountryCodeFE");
        } else {
            this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoPaisDestino"));
            return;
        }
        line.append(paisDestino + "\n");
        // *****CLIENTE
        MBPartner partner = new MBPartner(this.getM_ctx(), this.getInvoice().getC_BPartner_ID(), this.getTrxName());
        line.append(partner.getName() + "\n");
        // //*****DOMICILIO CLIENTE
        // String domicilioCliente;
        // 
        // if(this.getInvoice().getInvoice_Adress() != null){
        // domicilioCliente = this.getInvoice().getInvoice_Adress();
        // }
        // else{
        // this.setMessageError(Msg.translate(this.getM_ctx(), "CaeNoDomicilioCliente"));
        // return;
        // }
        // line.append(domicilioCliente+"\n");
        // *****ID IMPOSITIVO
        line.append(partner.getTaxID() + "\n");
        // *****IDIOMA COMPROBANTE
        line.append("1" + "\n");
        /*
			Pro_codigo       - String (C50)    - Código de producto         - Optativo
			Pro_ds           - String (C4000)  - Descripción de producto    - Obligatorio
			Pro_qty          - Decimal (N12,6) - Cantidad                   - Optativo
			Pro_umed         - Int(N2)         - Unidad de medida.          - Obligatorio 
			Pro_precio_uni   - Decimal (N12,6) - Precio unitario            - Optativo
			Pro_bonificacion - Decimal (N12,6) - Bonificación sobre el item - Optativo
			Pro_total_item   - Decimal (N13,2) - Importe total ítem         - Obligatorio
			*/
        line.append("ITEMS" + "\n");
        line.append(this.getInvoice().getLines().length + "\n");
        for (MInvoiceLine invoiceLine : this.getInvoice().getLines()) {
            line.append(invoiceLine.getM_Product().getName());
            line.append(":");
            line.append(invoiceLine.getQtyEntered());
            line.append(":");
            MUOM uom = MUOM.get(this.getM_ctx(), invoiceLine.getC_UOM_ID());
            line.append(uom.get_ValueAsString("UOMCodeFE"));
            line.append(":");
            line.append(invoiceLine.getPriceEntered());
            line.append(":");
            line.append(invoiceLine.getLineTotalAmt());
            line.append("\n");
        }
        // *****C_INVOICE_ID para seguimiento
        line.append(this.getInvoice().getC_Invoice_ID() + "\n");
        File textFile = new File(getPath() + "entrada.txt");
        FileWriter textOut;
        textOut = new FileWriter(textFile);
        textOut.write(line.toString());
        textOut.close();
    } catch (Exception ex) {
        this.setMessageError(Msg.translate(this.getM_ctx(), "caeErrorCreateInputFile"));
        log.log(Level.SEVERE, this.getMessageError(), ex);
    }
}
Also used : MDocType(org.compiere.model.MDocType) MUOM(org.compiere.model.MUOM) MCurrency(org.compiere.model.MCurrency) MInvoiceLine(org.compiere.model.MInvoiceLine) FileWriter(java.io.FileWriter) MClientInfo(org.compiere.model.MClientInfo) MBPartner(org.compiere.model.MBPartner) BigDecimal(java.math.BigDecimal) MOrgInfo(org.compiere.model.MOrgInfo) MLocation(org.compiere.model.MLocation) File(java.io.File)

Example 4 with MCurrency

use of org.compiere.model.MCurrency in project adempiere by adempiere.

the class InitialClientSetup method main.

public static void main(String[] args) {
    Adempiere.startupEnvironment(false);
    CLogMgt.setLevel(Level.CONFIG);
    String propFileName = Adempiere.getAdempiereHome() + File.separatorChar + "clientsetup.properties";
    if (args.length > 0)
        propFileName = args[0];
    ProcessInfo pi = new ProcessInfo("Initial Client Setup", 53161);
    pi.setAD_Client_ID(0);
    pi.setAD_User_ID(100);
    Properties prop = new Properties();
    try {
        prop.load(new FileInputStream(propFileName));
        pi.addParameter("ClientName", prop.getProperty("ClientName"), prop.getProperty("ClientName"));
        pi.addParameter("OrgValue", prop.getProperty("OrgValue"), prop.getProperty("OrgValue"));
        pi.addParameter("OrgName", prop.getProperty("OrgName"), prop.getProperty("OrgName"));
        pi.addParameter("AdminUserName", prop.getProperty("AdminUserName"), prop.getProperty("AdminUserName"));
        pi.addParameter("NormalUserName", prop.getProperty("NormalUserName"), prop.getProperty("NormalUserName"));
        if (prop.getProperty("CurrencyCode") != null) {
            MCurrency currency = MCurrency.get(Env.getCtx(), prop.getProperty("CurrencyCode"));
            if (currency != null)
                pi.addParameter("C_Currency_ID", currency.getC_Currency_ID(), currency.getISO_Code());
        }
        if (prop.getProperty("CountryCode") != null) {
            MCountry country = MCountry.get(Env.getCtx(), prop.getProperty("CountryCode"));
            if (country != null)
                pi.addParameter("C_Country_ID", country.getC_Country_ID(), country.getCountryCode());
        }
        pi.addParameter("C_Region_ID", prop.getProperty("C_Region_ID"), prop.getProperty("C_Region_ID"));
        pi.addParameter("CityName", prop.getProperty("CityName"), prop.getProperty("CityName"));
        pi.addParameter("C_City_ID", prop.getProperty("C_City_ID"), prop.getProperty("C_City_ID"));
        pi.addParameter("Postal", prop.getProperty("Postal"), prop.getProperty("Postal"));
        pi.addParameter("Address1", prop.getProperty("Address1"), prop.getProperty("Address1"));
        pi.addParameter("IsUseBPDimension", prop.getProperty("IsUseBPDimension"), prop.getProperty("IsUseBPDimension"));
        pi.addParameter("IsUseProductDimension", prop.getProperty("IsUseProductDimension"), prop.getProperty("IsUseProductDimension"));
        pi.addParameter("IsUseProjectDimension", prop.getProperty("IsUseProjectDimension"), prop.getProperty("IsUseProjectDimension"));
        pi.addParameter("IsUseCampaignDimension", prop.getProperty("IsUseCampaignDimension"), prop.getProperty("IsUseCampaignDimension"));
        pi.addParameter("IsUseSalesRegionDimension", prop.getProperty("IsUseSalesRegionDimension"), prop.getProperty("IsUseSalesRegionDimension"));
        pi.addParameter("CoAFile", prop.getProperty("CoAFile"), prop.getProperty("CoAFile"));
        pi.addParameter("Phone", prop.getProperty("Phone"), prop.getProperty("Phone"));
        pi.addParameter("Phone2", prop.getProperty("Phone2"), prop.getProperty("Phone2"));
        pi.addParameter("Fax", prop.getProperty("Fax"), prop.getProperty("Fax"));
        pi.addParameter("EMail", prop.getProperty("EMail"), prop.getProperty("EMail"));
        pi.addParameter("TaxID", prop.getProperty("TaxID"), prop.getProperty("TaxID"));
        pi.addParameter("Logo", prop.getProperty("Logo"), prop.getProperty("Logo"));
        pi.addParameter("StartDate", prop.getProperty("StartDate"), prop.getProperty("StartDate"));
        pi.addParameter("HistoryYears", prop.getProperty("HistoryYears"), prop.getProperty("HistoryYears"));
        pi.addParameter("DUNS", prop.getProperty("DUNS"), prop.getProperty("DUNS"));
        pi.addParameter("BankName", prop.getProperty("BankName"), prop.getProperty("BankName"));
        pi.addParameter("RoutingNo", prop.getProperty("RoutingNo"), prop.getProperty("RoutingNo"));
        pi.addParameter("AccountNo", prop.getProperty("AccountNo"), prop.getProperty("AccountNo"));
    } catch (Exception e) {
    // TODO: handle exception
    }
    InitialClientSetup setup = new InitialClientSetup();
    setup.startProcess(Env.getCtx(), pi, null);
}
Also used : MCountry(org.compiere.model.MCountry) MCurrency(org.compiere.model.MCurrency) ProcessInfo(org.compiere.process.ProcessInfo) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) AdempiereException(org.adempiere.exceptions.AdempiereException)

Example 5 with MCurrency

use of org.compiere.model.MCurrency in project adempiere by adempiere.

the class InitialClientSetup method doIt.

/**
	 * 	Process
	 *	@return info
	 *	@throws Exception
	 */
protected String doIt() throws Exception {
    log.info("InitialClientSetup" + ": ClientName=" + getClientName() + ", OrgValue=" + getOrgKey() + ", OrgName=" + getOrganizationName() + ", AdminUserName=" + getAdministrativeUserName() + ", NormalUserName=" + getNormalUserName() + ", C_Currency_ID=" + getCurrencyId() + ", C_Country_ID=" + getCountryId() + ", C_Region_ID=" + getRegionId() + ", CityName=" + getCityName() + ", C_City_ID=" + getCityId() + ", IsUseBPDimension=" + isBPAccounting() + ", IsUseProductDimension=" + isProductAccounting() + ", IsUseProjectDimension=" + isProjectAccounting() + ", IsUseCampaignDimension=" + isCampaignAccounting() + ", IsUseSalesRegionDimension=" + isSalesRegionAccounting() + ", ChartofAccountsFile=" + getChartofAccountsFile());
    // Validate Mandatory parameters
    if (getClientName() == null || getClientName().length() == 0 || getOrganizationName() == null || getOrganizationName().length() == 0 || getCurrencyId() <= 0 || getCountryId() <= 0 || getChartofAccountsFile() == null || getChartofAccountsFile().length() == 0)
        throw new IllegalArgumentException("Missing required parameters");
    //	Unique Client Name
    if (DB.executeUpdate("UPDATE AD_Client SET CreatedBy=0 WHERE Name=?", new Object[] { getClientName() }, false, null) != 0)
        throw new AdempiereException("@NotUnique@ " + getClientName());
    //	Unique User Names
    if (DB.executeUpdate("UPDATE AD_User SET CreatedBy=0 WHERE Name=?", new Object[] { getAdministrativeUserName() }, false, null) != 0)
        throw new AdempiereException("@NotUnique@ " + getAdministrativeUserName());
    if (DB.executeUpdate("UPDATE AD_User SET CreatedBy=0 WHERE Name=?", new Object[] { getNormalUserName() }, false, null) != 0)
        throw new AdempiereException("@NotUnique@ " + getNormalUserName());
    // City_ID overrides CityName if both used
    if (getCityId() > 0) {
        MCity city = MCity.get(getCtx(), getCityId());
        if (!city.getName().equals(getCityName())) {
            log.info("City name changed from " + getCityName() + " to " + city.getName());
            setCityName(city.getName());
        }
    }
    // Validate existence and read permissions on CoA file
    File chartofAccountsFile = new File(getChartofAccountsFile());
    if (!chartofAccountsFile.exists())
        throw new AdempiereException("CoaFile " + getChartofAccountsFile() + " does not exist");
    if (!chartofAccountsFile.canRead())
        throw new AdempiereException("Cannot read CoaFile " + getChartofAccountsFile());
    if (!chartofAccountsFile.isFile())
        throw new AdempiereException("CoaFile " + getChartofAccountsFile() + " is not a file");
    if (chartofAccountsFile.length() <= 0L)
        throw new AdempiereException("CoaFile " + getChartofAccountsFile() + " is empty");
    // Process
    MSetup setup = null;
    MCountry country = MCountry.get(getCtx(), getCountryId());
    try {
        Class<?> ppClass = Class.forName("org.compiere.model.MSetup_" + country.getCountryCode());
        if (ppClass != null)
            setup = (MSetup) ppClass.newInstance();
    } catch (//  NoClassDefFound
    Exception e) {
    // ignore as country specific setup class may not exist
    }
    if (setup == null)
        setup = new MSetup();
    setup.initialize(Env.getCtx(), WINDOW_THIS_PROCESS);
    if (!setup.createClient(getClientName(), getOrgKey(), getOrganizationName(), getAdministrativeUserName(), getNormalUserName(), getPhone(), getPhone2(), getFax(), getEMailAddress(), getTaxID(), getDUNS(), getLogo(), getCountryId())) {
        setup.rollback();
        throw new AdempiereException("Create client failed");
    }
    addLog(setup.getInfo());
    //  Generate Accounting
    MCurrency currency = MCurrency.get(getCtx(), getCurrencyId());
    KeyNamePair currencyKeyNamePair = new KeyNamePair(getCurrencyId(), currency.getDescription());
    if (!setup.createAccounting(currencyKeyNamePair, isProductAccounting(), isBPAccounting(), isProjectAccounting(), isCampaignAccounting(), isSalesRegionAccounting(), getStartDate(), getHistoryYears(), chartofAccountsFile)) {
        setup.rollback();
        throw new AdempiereException("@AccountSetupError@");
    }
    //  Generate Entities
    if (!setup.createEntities(getCountryId(), getCityName(), getRegionId(), getCurrencyId(), getZIP(), getAddress1())) {
        setup.rollback();
        throw new AdempiereException("@AccountSetupError@");
    }
    // Create Bank
    if (!Util.isEmpty(getBankName()) && !Util.isEmpty(getRoutingNo()) && !Util.isEmpty(getAccountNo())) {
        setup.createBank(getBankName(), getRoutingNo(), getAccountNo(), getCurrencyId());
    }
    // load chart of accounts
    if (!setup.importChart(chartofAccountsFile)) {
        setup.rollback();
        throw new AdempiereException("@AccountSetupError@");
    }
    addLog(setup.getInfo());
    //	Create Print Documents
    PrintUtil.setupPrintForm(setup.getAD_Client_ID());
    // Update translation after create a new tenant
    //Adempiere-53 Changes
    String whereClause = MLanguage.COLUMNNAME_IsSystemLanguage + "='Y' AND " + MLanguage.COLUMNNAME_IsActive + "='Y'";
    List<MLanguage> list = new Query(Env.getCtx(), MLanguage.Table_Name, whereClause, get_TrxName()).list();
    for (MLanguage lang : list) {
        log.fine("Updating Translation - " + lang);
        lang.maintain(true);
    }
    return "@OK@";
}
Also used : MCountry(org.compiere.model.MCountry) Query(org.compiere.model.Query) MCity(org.compiere.model.MCity) MCurrency(org.compiere.model.MCurrency) MLanguage(org.compiere.model.MLanguage) AdempiereException(org.adempiere.exceptions.AdempiereException) AdempiereException(org.adempiere.exceptions.AdempiereException) MSetup(org.compiere.model.MSetup) KeyNamePair(org.compiere.util.KeyNamePair) File(java.io.File)

Aggregations

MCurrency (org.compiere.model.MCurrency)5 File (java.io.File)3 BigDecimal (java.math.BigDecimal)3 FileWriter (java.io.FileWriter)2 AdempiereException (org.adempiere.exceptions.AdempiereException)2 MBPartner (org.compiere.model.MBPartner)2 MCountry (org.compiere.model.MCountry)2 MDocType (org.compiere.model.MDocType)2 InvoiceFiscalDocumentPrintManager (ar.com.ergio.print.fiscal.view.InvoiceFiscalDocumentPrintManager)1 FileInputStream (java.io.FileInputStream)1 Properties (java.util.Properties)1 MCity (org.compiere.model.MCity)1 MClientInfo (org.compiere.model.MClientInfo)1 MInvoiceLine (org.compiere.model.MInvoiceLine)1 MInvoicePaySchedule (org.compiere.model.MInvoicePaySchedule)1 MInvoiceTax (org.compiere.model.MInvoiceTax)1 MLanguage (org.compiere.model.MLanguage)1 MLocation (org.compiere.model.MLocation)1 MOrder (org.compiere.model.MOrder)1 MOrderPaySchedule (org.compiere.model.MOrderPaySchedule)1