Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

In this page you can find the example usage for java.math BigDecimal ONE.

Prototype

BigDecimal ONE

To view the source code for java.math BigDecimal ONE.

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:org.apache.ofbiz.accounting.invoice.InvoiceServices.java

private static BigDecimal calcHeaderAdj(Delegator delegator, GenericValue adj, String invoiceTypeId,
        String invoiceId, String invoiceItemSeqId, BigDecimal divisor, BigDecimal multiplier,
        BigDecimal baseAmount, int decimals, int rounding, GenericValue userLogin, LocalDispatcher dispatcher,
        Locale locale) {/*from  ww  w  .j av a  2s.c o  m*/
    BigDecimal adjAmount = ZERO;
    if (adj.get("amount") != null) {

        // pro-rate the amount
        BigDecimal amount = ZERO;
        if ("DONATION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) {
            amount = baseAmount;
        } else if (divisor.signum() != 0) { // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in essense
            // multiply first then divide to avoid rounding errors
            amount = baseAmount.multiply(multiplier).divide(divisor, decimals, rounding);
        }
        if (amount.signum() != 0) {
            Map<String, Object> createInvoiceItemContext = new HashMap<String, Object>();
            createInvoiceItemContext.put("invoiceId", invoiceId);
            createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator,
                    adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ"));
            createInvoiceItemContext.put("description", adj.get("description"));
            createInvoiceItemContext.put("quantity", BigDecimal.ONE);
            createInvoiceItemContext.put("amount", amount);
            createInvoiceItemContext.put("overrideGlAccountId", adj.get("overrideGlAccountId"));
            createInvoiceItemContext.put("taxAuthPartyId", adj.get("taxAuthPartyId"));
            createInvoiceItemContext.put("taxAuthGeoId", adj.get("taxAuthGeoId"));
            createInvoiceItemContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));
            createInvoiceItemContext.put("userLogin", userLogin);

            Map<String, Object> createInvoiceItemResult = null;
            try {
                createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Service/other problem creating InvoiceItem from order header adjustment",
                        module);
                return adjAmount;
            }
            if (ServiceUtil.isError(createInvoiceItemResult)) {
                return adjAmount;
            }

            // Create the OrderAdjustmentBilling record
            Map<String, Object> createOrderAdjustmentBillingContext = new HashMap<String, Object>();
            createOrderAdjustmentBillingContext.put("orderAdjustmentId", adj.getString("orderAdjustmentId"));
            createOrderAdjustmentBillingContext.put("invoiceId", invoiceId);
            createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createOrderAdjustmentBillingContext.put("amount", amount);
            createOrderAdjustmentBillingContext.put("userLogin", userLogin);

            try {
                dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
            } catch (GenericServiceException e) {
                return adjAmount;
            }

        }
        amount = amount.setScale(decimals, rounding);
        adjAmount = amount;
    } else if (adj.get("sourcePercentage") != null) {
        // pro-rate the amount
        BigDecimal percent = adj.getBigDecimal("sourcePercentage");
        percent = percent.divide(new BigDecimal(100), 100, rounding);
        BigDecimal amount = ZERO;
        // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in essense
        if (divisor.signum() != 0) {
            // multiply first then divide to avoid rounding errors
            amount = percent.multiply(divisor);
        }
        if (amount.signum() != 0) {
            Map<String, Object> createInvoiceItemContext = new HashMap<String, Object>();
            createInvoiceItemContext.put("invoiceId", invoiceId);
            createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator,
                    adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ"));
            createInvoiceItemContext.put("description", adj.get("description"));
            createInvoiceItemContext.put("quantity", BigDecimal.ONE);
            createInvoiceItemContext.put("amount", amount);
            createInvoiceItemContext.put("overrideGlAccountId", adj.get("overrideGlAccountId"));
            createInvoiceItemContext.put("taxAuthPartyId", adj.get("taxAuthPartyId"));
            createInvoiceItemContext.put("taxAuthGeoId", adj.get("taxAuthGeoId"));
            createInvoiceItemContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));
            createInvoiceItemContext.put("userLogin", userLogin);

            Map<String, Object> createInvoiceItemResult = null;
            try {
                createInvoiceItemResult = dispatcher.runSync("createInvoiceItem", createInvoiceItemContext);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Service/other problem creating InvoiceItem from order header adjustment",
                        module);
                return adjAmount;
            }
            if (ServiceUtil.isError(createInvoiceItemResult)) {
                return adjAmount;
            }

            // Create the OrderAdjustmentBilling record
            Map<String, Object> createOrderAdjustmentBillingContext = new HashMap<String, Object>();
            createOrderAdjustmentBillingContext.put("orderAdjustmentId", adj.getString("orderAdjustmentId"));
            createOrderAdjustmentBillingContext.put("invoiceId", invoiceId);
            createOrderAdjustmentBillingContext.put("invoiceItemSeqId", invoiceItemSeqId);
            createOrderAdjustmentBillingContext.put("amount", amount);
            createOrderAdjustmentBillingContext.put("userLogin", userLogin);

            try {
                dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
            } catch (GenericServiceException e) {
                return adjAmount;
            }

        }
        amount = amount.setScale(decimals, rounding);
        adjAmount = amount;
    }

    Debug.logInfo("adjAmount: " + adjAmount + ", divisor: " + divisor + ", multiplier: " + multiplier
            + ", invoiceTypeId: " + invoiceTypeId + ", invoiceId: " + invoiceId + ", itemSeqId: "
            + invoiceItemSeqId + ", decimals: " + decimals + ", rounding: " + rounding + ", adj: " + adj,
            module);
    return adjAmount;
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String PubBaseLegal() throws Exception {
    String pagina = "/index.xhtml";
    try {/*from  w  ww . j a v a2 s.  co  m*/

        LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
        User usuario = loginMB.getUser();
        if (this.getChkDestacado()) {
            ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
            HashMap filter = new HashMap();
            filter.put("ntipoconocimientoid", Constante.BASELEGAL);
            BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
            if (cant.intValue() >= 10) {
                this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                return "";
            }
        }
        if (!CollectionUtils.isEmpty(this.getListaTarget())) {
            for (BaseLegal v : this.getListaTarget()) {
                if (v.getNestadoid().equals(BigDecimal.ZERO)) {
                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                            "Debe seleccionar el estado de todos los vnculos agregados.");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                    return "";
                }
            }
        }
        if (this.getSelectedCategoria() != null) {
            this.getSelectedBaseLegal().setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
        }
        BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
        this.getSelectedBaseLegal()
                .setVnombre(StringUtils.capitalize(this.getSelectedBaseLegal().getVnombre()));
        this.getSelectedBaseLegal().setVnumero(
                this.getTipoNorma().concat(" - ").concat(StringUtils.upperCase(this.getNumeroNorma())));
        this.getSelectedBaseLegal().setNrangoid(this.getSelectedBaseLegal().getNrangoid());
        this.getSelectedBaseLegal()
                .setNgobnacional(this.getChkGobNacional() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal()
                .setNgobregional(this.getChkGobRegional() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setNgoblocal(this.getChkGobLocal() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal()
                .setNmancomunidades(this.getChkMancomunidades() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setVsumilla(this.getSelectedBaseLegal().getVsumilla().trim());
        this.getSelectedBaseLegal().setDfechapublicacion(new Date());
        this.getSelectedBaseLegal().setVtema(this.getSelectedBaseLegal().getVtema());
        this.getSelectedBaseLegal()
                .setNestadoid(BigDecimal.valueOf(Long.valueOf(Constante.ESTADO_BASELEGAL_PUBLICADO)));
        this.getSelectedBaseLegal().setVusuariomodificacion(usuario.getVlogin());
        this.getSelectedBaseLegal().setDfechamodificacion(new Date());
        service.saveOrUpdate(this.getSelectedBaseLegal());

        BaseLegalHistorialService serviceHistorial = (BaseLegalHistorialService) ServiceFinder
                .findBean("BaseLegalHistorialService");
        BaselegalHist hist = serviceHistorial
                .getLastHistorialByBaselegal(this.getSelectedBaseLegal().getNbaselegalid());

        BaselegalHist baseHist = new BaselegalHist();
        baseHist.setNhistorialid(serviceHistorial.getNextPK());
        baseHist.setNbaselegalid(this.getSelectedBaseLegal().getNbaselegalid());
        baseHist.setNcategoriaid(this.getSelectedBaseLegal().getNcategoriaid());
        baseHist.setVnombre(this.getSelectedBaseLegal().getVnombre());
        baseHist.setVnumero(this.getSelectedBaseLegal().getVnumero());
        baseHist.setNrangoid(this.getSelectedBaseLegal().getNrangoid());
        baseHist.setNgobnacional(this.getSelectedBaseLegal().getNgobnacional());
        baseHist.setNgobregional(this.getSelectedBaseLegal().getNgobregional());
        baseHist.setNgoblocal(this.getSelectedBaseLegal().getNgoblocal());
        baseHist.setNmancomunidades(this.getSelectedBaseLegal().getNmancomunidades());
        baseHist.setNdestacado(this.getSelectedBaseLegal().getNdestacado());
        baseHist.setVsumilla(this.getSelectedBaseLegal().getVsumilla());
        baseHist.setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
        baseHist.setVtema(this.getSelectedBaseLegal().getVtema());
        baseHist.setNactivo(this.getSelectedBaseLegal().getNactivo());
        baseHist.setNestadoid(this.getSelectedBaseLegal().getNestadoid());
        baseHist.setNversion(BigDecimal.valueOf(hist.getNversion().intValue() + 1));
        baseHist.setVusuariocreacion(usuario.getVlogin());
        baseHist.setDfechacreacion(new Date());
        baseHist.setVusuariomodificacion(this.getSelectedBaseLegal().getVusuariomodificacion());
        baseHist.setDfechamodificacion(this.getSelectedBaseLegal().getDfechamodificacion());
        serviceHistorial.saveOrUpdate(baseHist);

        Tbaselegal tbaselegal = new Tbaselegal();
        BeanUtils.copyProperties(tbaselegal, this.getSelectedBaseLegal());

        String ruta0 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                + BigDecimal.ZERO.toString() + "/";
        String ruta1 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                + baseHist.getNversion().toString() + "/";

        ArchivoService aservice = (ArchivoService) ServiceFinder.findBean("ArchivoService");
        Archivo archivo = aservice.getArchivoByBaseLegal(this.getSelectedBaseLegal());
        if (this.getUploadFile() != null) {
            archivo.setVnombre(this.getUploadFile().getFileName());
            archivo.setVruta(ruta0 + archivo.getVnombre());
            archivo.setVusuariomodificacion(usuario.getVlogin());
            archivo.setDfechamodificacion(new Date());
            aservice.saveOrUpdate(archivo);
            saveFile(ruta0);
        }

        ArchivoHistorialService aserviceHist = (ArchivoHistorialService) ServiceFinder
                .findBean("ArchivoHistorialService");
        ArchivoHist aHist = aserviceHist.getLastArchivoHistByBaseLegalHist(baseHist);

        ArchivoHist archivoHist = new ArchivoHist();
        archivoHist.setNarchivohistid(aserviceHist.getNextPK());
        archivoHist.setNhistorialid(baseHist.getNhistorialid());
        archivoHist.setNbaselegalid(baseHist.getNbaselegalid());
        archivoHist.setVnombre(archivo.getVnombre());
        archivoHist.setVruta(ruta1 + archivo.getVnombre());
        archivoHist.setVusuariocreacion(usuario.getVlogin());
        archivoHist.setDfechacreacion(new Date());
        aserviceHist.saveOrUpdate(archivoHist);
        saveFile(ruta1);

        VinculoBaseLegalService vservice = (VinculoBaseLegalService) ServiceFinder
                .findBean("VinculoBaseLegalService");
        vservice.deleteByBaseLegal(this.getSelectedBaseLegal());
        for (BaseLegal v : this.getListaTarget()) {
            TvinculoBaselegalId id = new TvinculoBaselegalId();
            id.setNbaselegalid(tbaselegal.getNbaselegalid());
            id.setNvinculoid(vservice.getNextPK());
            VinculoBaselegal vinculo = new VinculoBaselegal();
            vinculo.setId(id);
            vinculo.setTbaselegal(tbaselegal);
            vinculo.setNbaselegalvinculadaid(v.getNbaselegalid());
            vinculo.setNtipovinculo(v.getNestadoid());
            vinculo.setDfechacreacion(new Date());
            vinculo.setVusuariocreacion(usuario.getVlogin());
            vservice.saveOrUpdate(vinculo);

            BaseLegal blvinculada = service.getBaselegalById(v.getNbaselegalid());
            blvinculada.setNestadoid(v.getNestadoid());
            blvinculada.setDfechamodificacion(new Date());
            blvinculada.setVusuariomodificacion(usuario.getVlogin());
            service.saveOrUpdate(blvinculada);

            if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_MODIFICADA)
                    || v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_CONCORDADO)) {

                ConocimientoService cservice = (ConocimientoService) ServiceFinder
                        .findBean("ConocimientoService");
                List<Consulta> listaConocimientos = cservice
                        .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                for (Consulta c : listaConocimientos) {
                    Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                    conocimiento.setDfechamodificacion(new Date());
                    conocimiento.setVusuariomodificacion(usuario.getVlogin());
                    String descHtml = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                            "html.txt");
                    String descPlain = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                            "plain.txt");
                    cservice.saveOrUpdate(conocimiento);

                    HistorialService historialService = (HistorialService) ServiceFinder
                            .findBean("HistorialService");
                    Historial lastHistorial = historialService
                            .getLastHistorialByConocimiento(conocimiento.getNconocimientoid());
                    int lastversion;
                    if (lastHistorial != null) {
                        lastversion = lastHistorial.getNnumversion().intValue();
                    } else {
                        lastversion = 0;
                    }
                    String newpath = "";
                    if (conocimiento.getNtipoconocimientoid().equals(Constante.BASELEGAL)) {
                        newpath = "bl/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.BUENAPRACTICA)) {
                        newpath = "bp/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.CONTENIDO)) {
                        newpath = "ct/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.OPORTUNIDADMEJORA)) {
                        newpath = "om/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.PREGUNTAS)) {
                        newpath = "pr/";
                    } else if (conocimiento.getNtipoconocimientoid().equals(Constante.WIKI)) {
                        newpath = "wk/";
                    }

                    String url = newpath.concat(conocimiento.getNconocimientoid().toString()).concat("/")
                            .concat(Integer.toString(lastversion + 1)).concat("/");

                    ThistorialId thistorialId = new ThistorialId();
                    thistorialId.setNconocimientoid(conocimiento.getNconocimientoid());
                    thistorialId.setNhistorialid(historialService.getNextPK());
                    Historial historial = new Historial();
                    historial.setId(thistorialId);
                    historial.setNtipoconocimientoid(conocimiento.getNtipoconocimientoid());
                    historial.setNcategoriaid(conocimiento.getNcategoriaid());
                    historial.setVtitulo(conocimiento.getVtitulo());
                    historial.setNactivo(BigDecimal.ONE);
                    historial.setNsituacionid(conocimiento.getNsituacionid());
                    historial.setVruta(url);
                    historial.setNnumversion(BigDecimal.valueOf(lastversion + 1));
                    historial.setDfechacreacion(new Date());
                    historial.setVusuariocreacion(usuario.getVlogin());
                    historialService.saveOrUpdate(historial);

                    GcmFileUtils.writeStringToFileServer(url, "html.txt", descHtml);
                    GcmFileUtils.writeStringToFileServer(url, "plain.txt", descPlain);

                    SeccionService seccionService = (SeccionService) ServiceFinder.findBean("SeccionService");
                    SeccionHistService seccionHistService = (SeccionHistService) ServiceFinder
                            .findBean("SeccionHistService");
                    List<Seccion> listaSecc = seccionService
                            .getSeccionesByConocimiento(conocimiento.getNconocimientoid());
                    if (!CollectionUtils.isEmpty(listaSecc)) {
                        String url0 = conocimiento.getVruta().concat("s");
                        String url1 = url.concat("s");
                        for (Seccion seccion : listaSecc) {
                            seccion.setDetalleHtml(
                                    GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                            ruta0 = url0.concat(seccion.getNorden().toString()).concat("/");
                            seccion.setVruta(ruta0);
                            seccion.setDfechamodificacion(new Date());
                            seccion.setVusuariomodificacion(usuario.getVlogin());
                            seccionService.saveOrUpdate(seccion);

                            seccion.setDetallePlain(Jsoup.parse(seccion.getDetalleHtml()).text());

                            ruta1 = url1.concat(seccion.getNorden().toString()).concat("/");
                            TseccionHistId tseccionHistId = new TseccionHistId();
                            tseccionHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                            tseccionHistId.setNhistorialid(thistorialId.getNhistorialid());
                            tseccionHistId.setNseccionhid(seccionHistService.getNextPK());
                            SeccionHist seccionHist = new SeccionHist();
                            seccionHist.setId(tseccionHistId);
                            seccionHist.setNorden(seccion.getNorden());
                            seccionHist.setVruta(ruta1);
                            seccionHist.setVtitulo(seccion.getVtitulo());
                            seccionHist.setVusuariocreacion(usuario.getVlogin());
                            seccionHist.setDfechacreacion(new Date());
                            seccionHistService.saveOrUpdate(seccionHist);

                            GcmFileUtils.writeStringToFileServer(ruta1, "html.txt", seccion.getDetalleHtml());
                            GcmFileUtils.writeStringToFileServer(ruta1, "plain.txt", seccion.getDetallePlain());
                        }
                    }

                    VinculoService vinculoService = (VinculoService) ServiceFinder.findBean("VinculoService");
                    Vinculo vinculoC = new Vinculo();
                    vinculoC.setNvinculoid(vinculoService.getNextPK());
                    vinculoC.setNconocimientoid(conocimiento.getNconocimientoid());
                    vinculoC.setNconocimientovinc(tbaselegal.getNbaselegalid());
                    vinculoC.setNtipoconocimientovinc(Constante.BASELEGAL);
                    vinculoC.setDfechacreacion(new Date());
                    vinculoC.setVusuariocreacion(usuario.getVlogin());
                    vinculoService.saveOrUpdate(vinculoC);

                    List<Vinculo> vinculos = vinculoService
                            .getVinculosByConocimiento(conocimiento.getNtipoconocimientoid());
                    VinculoHistService vinculoHistService = (VinculoHistService) ServiceFinder
                            .findBean("VinculoHistService");
                    for (Vinculo vinc : vinculos) {
                        TvinculoHistId vinculoHistId = new TvinculoHistId();
                        vinculoHistId.setNvinculohid(vinculoHistService.getNextPK());
                        vinculoHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                        vinculoHistId.setNhistorialid(thistorialId.getNhistorialid());
                        VinculoHist vinculoHist = new VinculoHist();
                        vinculoHist.setId(vinculoHistId);
                        vinculoHist.setNconocimientovinc(vinc.getNconocimientovinc());
                        vinculoHist.setDfechacreacion(new Date());
                        vinculoHist.setVusuariocreacion(usuario.getVlogin());
                        vinculoHistService.saveOrUpdate(vinculoHist);
                    }
                }
            } else if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_DEROGADA)) {
                ConocimientoService cservice = (ConocimientoService) ServiceFinder
                        .findBean("ConocimientoService");
                List<Consulta> listaConocimientos = cservice
                        .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                for (Consulta c : listaConocimientos) {
                    Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                    conocimiento.setNflgvinculo(BigDecimal.ONE);
                    conocimiento.setDfechamodificacion(new Date());
                    conocimiento.setVusuariomodificacion(usuario.getVlogin());
                }
            }

            VinculoBaselegalHistorialService vserviceHist = (VinculoBaselegalHistorialService) ServiceFinder
                    .findBean("VinculoBaselegalHistorialService");
            VinculoBaselegalHist vinculoHist = new VinculoBaselegalHist();
            vinculoHist.setNvinculohistid(vserviceHist.getNextPK());
            vinculoHist.setNhistorialid(baseHist.getNhistorialid());
            vinculoHist.setNbaselegalid(baseHist.getNbaselegalid());
            vinculoHist.setNbaselegalvinculadaid(v.getNbaselegalid());
            vinculoHist.setNtipovinculo(v.getNestadoid());
            vinculoHist.setDfechacreacion(new Date());
            vinculoHist.setVusuariocreacion(usuario.getVlogin());
            vserviceHist.saveOrUpdate(vinculoHist);
        }

        AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
        this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
        this.getSelectedAsignacion().setDfechaatencion(new Date());
        this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("8")));
        serviceasig.saveOrUpdate(this.getSelectedAsignacion());
        loginMB.refreshNotifications();
        pagina = "/index.xhtml";
        return pagina;

    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return pagina;
}

From source file:org.ofbiz.accounting.invoice.InvoiceServices.java

public static Map<String, Object> updatePaymentApplicationDefBd(DispatchContext dctx,
        Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    if (DECIMALS == -1 || ROUNDING == -1) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource, "AccountingAritmeticPropertiesNotConfigured", locale));
    }/*from  w  w w  .j  a  v a  2s  .  co  m*/

    if (!context.containsKey("useHighestAmount")) {
        context.put("useHighestAmount", "Y");
    }

    String defaultInvoiceProcessing = EntityUtilProperties.getPropertyValue("AccountingConfig",
            "invoiceProcessing", delegator);

    boolean debug = true; // show processing messages in the log..or not....

    // a 'y' in invoiceProssesing will reverse the default processing
    String changeProcessing = (String) context.get("invoiceProcessing");
    String invoiceId = (String) context.get("invoiceId");
    String invoiceItemSeqId = (String) context.get("invoiceItemSeqId");
    String paymentId = (String) context.get("paymentId");
    String toPaymentId = (String) context.get("toPaymentId");
    String paymentApplicationId = (String) context.get("paymentApplicationId");
    BigDecimal amountApplied = (BigDecimal) context.get("amountApplied");
    String billingAccountId = (String) context.get("billingAccountId");
    String taxAuthGeoId = (String) context.get("taxAuthGeoId");
    String useHighestAmount = (String) context.get("useHighestAmount");

    List<String> errorMessageList = FastList.newInstance();

    if (debug)
        Debug.logInfo("updatePaymentApplicationDefBd input parameters..." + " defaultInvoiceProcessing: "
                + defaultInvoiceProcessing + " changeDefaultInvoiceProcessing: " + changeProcessing
                + " useHighestAmount: " + useHighestAmount + " paymentApplicationId: " + paymentApplicationId
                + " PaymentId: " + paymentId + " InvoiceId: " + invoiceId + " InvoiceItemSeqId: "
                + invoiceItemSeqId + " BillingAccountId: " + billingAccountId + " toPaymentId: " + toPaymentId
                + " amountApplied: " + amountApplied + " TaxAuthGeoId: " + taxAuthGeoId, module);

    if (changeProcessing == null) {
        changeProcessing = "N"; // not provided, so no change
    }

    boolean invoiceProcessing = true;
    if (defaultInvoiceProcessing.equals("YY")) {
        invoiceProcessing = true;
    } else if (defaultInvoiceProcessing.equals("NN")) {
        invoiceProcessing = false;
    } else if (defaultInvoiceProcessing.equals("Y")) {
        invoiceProcessing = !"Y".equals(changeProcessing);
    } else if (defaultInvoiceProcessing.equals("N")) {
        invoiceProcessing = "Y".equals(changeProcessing);
    }

    // on a new paymentApplication check if only billing or invoice or tax
    // id is provided not 2,3... BUT a combination of billingAccountId and invoiceId is permitted - that's how you use a
    // Billing Account to pay for an Invoice
    if (paymentApplicationId == null) {
        int count = 0;
        if (invoiceId != null)
            count++;
        if (toPaymentId != null)
            count++;
        if (billingAccountId != null)
            count++;
        if (taxAuthGeoId != null)
            count++;
        if ((billingAccountId != null) && (invoiceId != null))
            count--;
        if (count != 1) {
            errorMessageList.add(UtilProperties.getMessage(resource,
                    "AccountingSpecifyInvoiceToPaymentBillingAccountTaxGeoId", locale));
        }
    }

    // avoid null pointer exceptions.
    if (amountApplied == null)
        amountApplied = ZERO;
    // makes no sense to have an item numer without an invoice number
    if (invoiceId == null)
        invoiceItemSeqId = null;

    // retrieve all information and perform checking on the retrieved info.....

    // Payment.....
    BigDecimal paymentApplyAvailable = ZERO;
    // amount available on the payment reduced by the already applied amounts
    BigDecimal amountAppliedMax = ZERO;
    // the maximum that can be applied taking payment,invoice,invoiceitem,billing account in concideration
    // if maxApplied is missing, this value can be used,
    // Payment this should be checked after the invoice checking because it is possible the currency is changed
    GenericValue payment = null;
    String currencyUomId = null;
    if (paymentId == null || paymentId.equals("")) {
        errorMessageList
                .add(UtilProperties.getMessage(resource, "AccountingPaymentIdBlankNotSupplied", locale));
    } else {
        try {
            payment = EntityQuery.use(delegator).from("Payment").where("paymentId", paymentId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (payment == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentRecordNotFound",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }
        paymentApplyAvailable = payment.getBigDecimal("amount")
                .subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING);

        if (payment.getString("statusId").equals("PMNT_CANCELLED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentCancelled",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }
        if (payment.getString("statusId").equals("PMNT_CONFIRMED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentConfirmed",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }

        currencyUomId = payment.getString("currencyUomId");

        // if the amount to apply is 0 give it amount the payment still need
        // to apply
        if (amountApplied.signum() == 0) {
            amountAppliedMax = paymentApplyAvailable;
        }

    }

    // the "TO" Payment.....
    BigDecimal toPaymentApplyAvailable = ZERO;
    GenericValue toPayment = null;
    if (toPaymentId != null && !toPaymentId.equals("")) {
        try {
            toPayment = EntityQuery.use(delegator).from("Payment").where("paymentId", toPaymentId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (toPayment == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentRecordNotFound",
                    UtilMisc.toMap("paymentId", toPaymentId), locale));
        }
        toPaymentApplyAvailable = toPayment.getBigDecimal("amount")
                .subtract(PaymentWorker.getPaymentApplied(toPayment)).setScale(DECIMALS, ROUNDING);

        if (toPayment.getString("statusId").equals("PMNT_CANCELLED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentCancelled",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }
        if (toPayment.getString("statusId").equals("PMNT_CONFIRMED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentConfirmed",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }

        // if the amount to apply is less then required by the payment reduce it
        if (amountAppliedMax.compareTo(toPaymentApplyAvailable) > 0) {
            amountAppliedMax = toPaymentApplyAvailable;
        }

        if (paymentApplicationId == null) {
            // only check for new application records, update on existing records is checked in the paymentApplication section
            if (toPaymentApplyAvailable.signum() == 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentAlreadyApplied",
                        UtilMisc.toMap("paymentId", toPaymentId), locale));
            } else {
                // check here for too much application if a new record is
                // added (paymentApplicationId == null)
                if (amountApplied.compareTo(toPaymentApplyAvailable) > 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentLessRequested",
                            UtilMisc.<String, Object>toMap("paymentId", toPaymentId, "paymentApplyAvailable",
                                    toPaymentApplyAvailable, "amountApplied", amountApplied, "isoCode",
                                    currencyUomId),
                            locale));
                }
            }
        }

        // check if at least one send is the same as one receiver on the other payment
        if (!payment.getString("partyIdFrom").equals(toPayment.getString("partyIdTo"))
                && !payment.getString("partyIdTo").equals(toPayment.getString("partyIdFrom"))) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingFromPartySameToParty", locale));
        }

        if (debug)
            Debug.logInfo("toPayment info retrieved and checked...", module);
    }

    // assign payment to billing account if the invoice is assigned to this billing account
    if (invoiceId != null) {
        GenericValue invoice = null;
        try {
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", invoiceId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }

        if (invoice == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceNotFound",
                    UtilMisc.toMap("invoiceId", invoiceId), locale));
        } else {
            if (invoice.getString("billingAccountId") != null) {
                billingAccountId = invoice.getString("billingAccountId");
            }
        }
    }

    // billing account
    GenericValue billingAccount = null;
    if (billingAccountId != null && !billingAccountId.equals("")) {
        try {
            billingAccount = EntityQuery.use(delegator).from("BillingAccount")
                    .where("billingAccountId", billingAccountId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (billingAccount == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingBillingAccountNotFound",
                    UtilMisc.toMap("billingAccountId", billingAccountId), locale));
        }
        // check the currency
        if (billingAccount.get("accountCurrencyUomId") != null && currencyUomId != null
                && !billingAccount.getString("accountCurrencyUomId").equals(currencyUomId)) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingBillingAccountCurrencyProblem",
                    UtilMisc.toMap("billingAccountId", billingAccountId, "accountCurrencyUomId",
                            billingAccount.getString("accountCurrencyUomId"), "paymentId", paymentId,
                            "paymentCurrencyUomId", currencyUomId),
                    locale));
        }

        if (debug)
            Debug.logInfo("Billing Account info retrieved and checked...", module);
    }

    // get the invoice (item) information
    BigDecimal invoiceApplyAvailable = ZERO;
    // amount available on the invoice reduced by the already applied amounts
    BigDecimal invoiceItemApplyAvailable = ZERO;
    // amount available on the invoiceItem reduced by the already applied amounts
    GenericValue invoice = null;
    GenericValue invoiceItem = null;
    if (invoiceId != null) {
        try {
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", invoiceId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }

        if (invoice == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceNotFound",
                    UtilMisc.toMap("invoiceId", invoiceId), locale));
        } else { // check the invoice and when supplied the invoice item...

            if (invoice.getString("statusId").equals("INVOICE_CANCELLED")) {
                errorMessageList
                        .add(UtilProperties.getMessage(resource, "AccountingInvoiceCancelledCannotApplyTo",
                                UtilMisc.toMap("invoiceId", invoiceId), locale));
            }

            // check the currency
            if (currencyUomId != null && invoice.get("currencyUomId") != null
                    && !currencyUomId.equals(invoice.getString("currencyUomId"))) {
                Debug.logInfo(
                        UtilProperties.getMessage(resource, "AccountingInvoicePaymentCurrencyProblem",
                                UtilMisc.toMap("invoiceCurrency", invoice.getString("currencyUomId"),
                                        "paymentCurrency", payment.getString("currencyUomId")),
                                locale),
                        module);
                Debug.logInfo("will try to apply payment on the actualCurrency amount on payment", module);

                if (payment.get("actualCurrencyAmount") == null || payment.get("actualCurrencyUomId") == null) {
                    errorMessageList.add(
                            "Actual amounts are required in the currency of the invoice to make this work....");
                } else {
                    currencyUomId = payment.getString("actualCurrencyUomId");
                    if (!currencyUomId.equals(invoice.getString("currencyUomId"))) {
                        errorMessageList.add("actual currency on payment (" + currencyUomId
                                + ") not the same as original invoice currency ("
                                + invoice.getString("currencyUomId") + ")");
                    }
                }
                paymentApplyAvailable = payment.getBigDecimal("actualCurrencyAmount")
                        .subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING);
                if (amountApplied.signum() == 0) {
                    amountAppliedMax = paymentApplyAvailable;
                }
            }

            // check if the invoice already covered by payments
            BigDecimal invoiceTotal = InvoiceWorker.getInvoiceTotal(invoice);
            invoiceApplyAvailable = InvoiceWorker.getInvoiceNotApplied(invoice);

            // adjust the amountAppliedMax value if required....
            if (invoiceApplyAvailable.compareTo(amountAppliedMax) < 0) {
                amountAppliedMax = invoiceApplyAvailable;
            }

            if (invoiceTotal.signum() == 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceTotalZero",
                        UtilMisc.toMap("invoiceId", invoiceId), locale));
            } else if (paymentApplicationId == null) {
                // only check for new records here...updates are checked in the paymentApplication section
                if (invoiceApplyAvailable.signum() == 0) {
                    errorMessageList
                            .add(UtilProperties.getMessage(resource, "AccountingInvoiceCompletelyApplied",
                                    UtilMisc.toMap("invoiceId", invoiceId), locale));
                }
                // check here for too much application if a new record(s) are
                // added (paymentApplicationId == null)
                else if (amountApplied.compareTo(invoiceApplyAvailable) > 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceLessRequested",
                            UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "invoiceApplyAvailable",
                                    invoiceApplyAvailable, "amountApplied", amountApplied, "isoCode",
                                    invoice.getString("currencyUomId")),
                            locale));
                }
            }

            // check if at least one sender is the same as one receiver on the invoice
            if (!payment.getString("partyIdFrom").equals(invoice.getString("partyId"))
                    && !payment.getString("partyIdTo").equals(invoice.getString("partyIdFrom"))) {
                errorMessageList
                        .add(UtilProperties.getMessage(resource, "AccountingFromPartySameToParty", locale));
            }

            if (debug)
                Debug.logInfo("Invoice info retrieved and checked ...", module);
        }

        // if provided check the invoice item.
        if (invoiceItemSeqId != null) {
            // when itemSeqNr not provided delay checking on invoiceItemSeqId
            try {
                invoiceItem = EntityQuery.use(delegator).from("InvoiceItem")
                        .where("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId).queryOne();
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(e.getMessage());
            }

            if (invoiceItem == null) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceItemNotFound",
                        UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId), locale));
            } else {
                if (invoice.get("currencyUomId") != null && currencyUomId != null
                        && !invoice.getString("currencyUomId").equals(currencyUomId)) {
                    errorMessageList.add(UtilProperties.getMessage(resource,
                            "AccountingInvoicePaymentCurrencyProblem", UtilMisc.toMap("paymentCurrencyId",
                                    currencyUomId, "itemCurrency", invoice.getString("currencyUomId")),
                            locale));
                }

                // get the invoice item applied value
                BigDecimal quantity = null;
                if (invoiceItem.get("quantity") == null) {
                    quantity = BigDecimal.ONE;
                } else {
                    quantity = invoiceItem.getBigDecimal("quantity").setScale(DECIMALS, ROUNDING);
                }
                invoiceItemApplyAvailable = invoiceItem.getBigDecimal("amount").multiply(quantity)
                        .setScale(DECIMALS, ROUNDING)
                        .subtract(InvoiceWorker.getInvoiceItemApplied(invoiceItem));
                // check here for too much application if a new record is added
                // (paymentApplicationId == null)
                if (paymentApplicationId == null && amountApplied.compareTo(invoiceItemApplyAvailable) > 0) {
                    // new record
                    errorMessageList.add("Invoice(" + invoiceId + ") item(" + invoiceItemSeqId + ") has  "
                            + invoiceItemApplyAvailable + " to apply but " + amountApplied + " is requested\n");
                    String uomId = invoice.getString("currencyUomId");
                    errorMessageList.add(UtilProperties.getMessage(resource,
                            "AccountingInvoiceItemLessRequested",
                            UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "invoiceItemSeqId",
                                    invoiceItemSeqId, "invoiceItemApplyAvailable", invoiceItemApplyAvailable,
                                    "amountApplied", amountApplied, "isoCode", uomId),
                            locale));
                }
            }
            if (debug)
                Debug.logInfo(
                        "InvoiceItem info retrieved and checked against the Invoice (currency and amounts) ...",
                        module);
        }
    }

    // check this at the end because the invoice can change the currency.......
    if (paymentApplicationId == null) {
        // only check for new application records, update on existing records is checked in the paymentApplication section
        if (paymentApplyAvailable.signum() == 0) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentAlreadyApplied",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        } else {
            // check here for too much application if a new record is
            // added (paymentApplicationId == null)
            if (amountApplied.compareTo(paymentApplyAvailable) > 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentLessRequested",
                        UtilMisc.<String, Object>toMap("paymentId", paymentId, "paymentApplyAvailable",
                                paymentApplyAvailable, "amountApplied", amountApplied, "isoCode",
                                currencyUomId),
                        locale));
            }
        }
    }

    // get the application record if the applicationId is supplied if not
    // create empty record.
    BigDecimal newInvoiceApplyAvailable = invoiceApplyAvailable;
    // amount available on the invoice taking into account if the invoiceItemnumber has changed
    BigDecimal newInvoiceItemApplyAvailable = invoiceItemApplyAvailable;
    // amount available on the invoiceItem taking into account if the itemnumber has changed
    BigDecimal newToPaymentApplyAvailable = toPaymentApplyAvailable;
    BigDecimal newPaymentApplyAvailable = paymentApplyAvailable;
    GenericValue paymentApplication = null;
    if (paymentApplicationId == null) {
        paymentApplication = delegator.makeValue("PaymentApplication");
        // prepare for creation
    } else { // retrieve existing paymentApplication
        try {
            paymentApplication = EntityQuery.use(delegator).from("PaymentApplication")
                    .where("paymentApplicationId", paymentApplicationId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }

        if (paymentApplication == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentApplicationNotFound",
                    UtilMisc.toMap("paymentApplicationId", paymentApplicationId), locale));
            paymentApplicationId = null;
        } else {

            // if both invoiceId and BillingId is entered there was
            // obviously a change
            // only take the newly entered item, same for tax authority and toPayment
            if (paymentApplication.get("invoiceId") == null && invoiceId != null) {
                billingAccountId = null;
                taxAuthGeoId = null;
                toPaymentId = null;
            } else if (paymentApplication.get("toPaymentId") == null && toPaymentId != null) {
                invoiceId = null;
                invoiceItemSeqId = null;
                taxAuthGeoId = null;
                billingAccountId = null;
            } else if (paymentApplication.get("billingAccountId") == null && billingAccountId != null) {
                invoiceId = null;
                invoiceItemSeqId = null;
                toPaymentId = null;
                taxAuthGeoId = null;
            } else if (paymentApplication.get("taxAuthGeoId") == null && taxAuthGeoId != null) {
                invoiceId = null;
                invoiceItemSeqId = null;
                toPaymentId = null;
                billingAccountId = null;
            }

            // check if the payment for too much application if an existing
            // application record is changed
            if (paymentApplyAvailable.compareTo(ZERO) == 0) {
                newPaymentApplyAvailable = paymentApplyAvailable
                        .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                        .setScale(DECIMALS, ROUNDING);
            } else {
                newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplyAvailable)
                        .subtract(amountApplied).setScale(DECIMALS, ROUNDING);
            }
            if (newPaymentApplyAvailable.compareTo(ZERO) < 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentNotEnough",
                        UtilMisc.<String, Object>toMap("paymentId", paymentId, "paymentApplyAvailable",
                                paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")),
                                "amountApplied", amountApplied),
                        locale));
            }

            if (invoiceId != null) {
                // only when we are processing an invoice on existing paymentApplication check invoice item for to much application if the invoice
                // number did not change
                if (invoiceId.equals(paymentApplication.getString("invoiceId"))) {
                    // check if both the itemNumbers are null then this is a
                    // record for the whole invoice
                    if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") == null) {
                        newInvoiceApplyAvailable = invoiceApplyAvailable
                                .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (invoiceApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList.add(UtilProperties.getMessage(resource,
                                    "AccountingInvoiceNotEnough", UtilMisc.<String, Object>toMap("tooMuch",
                                            newInvoiceApplyAvailable.negate(), "invoiceId", invoiceId),
                                    locale));
                        }
                    } else if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") != null) {
                        // check if the item number changed from a real Item number to a null value
                        newInvoiceApplyAvailable = invoiceApplyAvailable
                                .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (invoiceApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList.add(UtilProperties.getMessage(resource,
                                    "AccountingInvoiceNotEnough", UtilMisc.<String, Object>toMap("tooMuch",
                                            newInvoiceApplyAvailable.negate(), "invoiceId", invoiceId),
                                    locale));
                        }
                    } else if (invoiceItemSeqId != null && paymentApplication.get("invoiceItemSeqId") == null) {
                        // check if the item number changed from a null value to
                        // a real Item number
                        newInvoiceItemApplyAvailable = invoiceItemApplyAvailable.subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (newInvoiceItemApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList
                                    .add(UtilProperties.getMessage(resource, "AccountingItemInvoiceNotEnough",
                                            UtilMisc.<String, Object>toMap("tooMuch",
                                                    newInvoiceItemApplyAvailable.negate(), "invoiceId",
                                                    invoiceId, "invoiceItemSeqId", invoiceItemSeqId),
                                            locale));
                        }
                    } else if (invoiceItemSeqId.equals(paymentApplication.getString("invoiceItemSeqId"))) {
                        // check if the real item numbers the same
                        // item number the same numeric value
                        newInvoiceItemApplyAvailable = invoiceItemApplyAvailable
                                .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (newInvoiceItemApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList
                                    .add(UtilProperties.getMessage(resource, "AccountingItemInvoiceNotEnough",
                                            UtilMisc.<String, Object>toMap("tooMuch",
                                                    newInvoiceItemApplyAvailable.negate(), "invoiceId",
                                                    invoiceId, "invoiceItemSeqId", invoiceItemSeqId),
                                            locale));
                        }
                    } else {
                        // item number changed only check new item
                        newInvoiceItemApplyAvailable = invoiceItemApplyAvailable.add(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (newInvoiceItemApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList
                                    .add(UtilProperties.getMessage(resource, "AccountingItemInvoiceNotEnough",
                                            UtilMisc.<String, Object>toMap("tooMuch",
                                                    newInvoiceItemApplyAvailable.negate(), "invoiceId",
                                                    invoiceId, "invoiceItemSeqId", invoiceItemSeqId),
                                            locale));
                        }
                    }

                    // if the amountApplied = 0 give it the higest possible
                    // value
                    if (amountApplied.signum() == 0) {
                        if (newInvoiceItemApplyAvailable.compareTo(newPaymentApplyAvailable) < 0) {
                            amountApplied = newInvoiceItemApplyAvailable;
                            // from the item number
                        } else {
                            amountApplied = newPaymentApplyAvailable;
                            // from the payment
                        }
                    }

                    // check the invoice
                    newInvoiceApplyAvailable = invoiceApplyAvailable
                            .add(paymentApplication.getBigDecimal("amountApplied").subtract(amountApplied))
                            .setScale(DECIMALS, ROUNDING);
                    if (newInvoiceApplyAvailable.compareTo(ZERO) < 0) {
                        errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceNotEnough",
                                UtilMisc.<String, Object>toMap("tooMuch",
                                        invoiceApplyAvailable
                                                .add(paymentApplication.getBigDecimal("amountApplied"))
                                                .subtract(amountApplied),
                                        "invoiceId", invoiceId),
                                locale));
                    }
                }
            }

            // check the toPayment account when only the amountApplied has
            // changed,
            if (toPaymentId != null && toPaymentId.equals(paymentApplication.getString("toPaymentId"))) {
                newToPaymentApplyAvailable = toPaymentApplyAvailable
                        .subtract(paymentApplication.getBigDecimal("amountApplied")).add(amountApplied)
                        .setScale(DECIMALS, ROUNDING);
                if (newToPaymentApplyAvailable.compareTo(ZERO) < 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentNotEnough",
                            UtilMisc.<String, Object>toMap("paymentId", toPaymentId, "paymentApplyAvailable",
                                    newToPaymentApplyAvailable, "amountApplied", amountApplied),
                            locale));
                }
            } else if (toPaymentId != null) {
                // billing account entered number has changed so we have to
                // check the new billing account number.
                newToPaymentApplyAvailable = toPaymentApplyAvailable.add(amountApplied).setScale(DECIMALS,
                        ROUNDING);
                if (newToPaymentApplyAvailable.compareTo(ZERO) < 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentNotEnough",
                            UtilMisc.<String, Object>toMap("paymentId", toPaymentId, "paymentApplyAvailable",
                                    newToPaymentApplyAvailable, "amountApplied", amountApplied),
                            locale));
                }

            }
        }
        if (debug)
            Debug.logInfo("paymentApplication record info retrieved and checked...", module);
    }

    // show the maximumus what can be added in the payment application file.
    String toMessage = null; // prepare for success message
    if (debug) {
        String extra = "";
        if (invoiceItemSeqId != null) {
            extra = " Invoice item(" + invoiceItemSeqId + ") amount not yet applied: "
                    + newInvoiceItemApplyAvailable;
        }
        Debug.logInfo("checking finished, start processing with the following data... ", module);
        if (invoiceId != null) {
            Debug.logInfo(" Invoice(" + invoiceId + ") amount not yet applied: " + newInvoiceApplyAvailable
                    + extra + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable
                    + " Requested amount to apply:" + amountApplied, module);
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToInvoice",
                    UtilMisc.toMap("invoiceId", invoiceId), locale);
            if (extra.length() > 0)
                toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToInvoiceItem",
                        UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId), locale);
        }
        if (toPaymentId != null) {
            Debug.logInfo(" toPayment(" + toPaymentId + ") amount not yet applied: "
                    + newToPaymentApplyAvailable + " Payment(" + paymentId + ") amount not yet applied: "
                    + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, module);
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToPayment",
                    UtilMisc.toMap("paymentId", toPaymentId), locale);
        }
        if (taxAuthGeoId != null) {
            Debug.logInfo(
                    " taxAuthGeoId(" + taxAuthGeoId + ")  Payment(" + paymentId + ") amount not yet applied: "
                            + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied,
                    module);
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToTax",
                    UtilMisc.toMap("taxAuthGeoId", taxAuthGeoId), locale);
        }
    }
    // if the amount to apply was not provided or was zero fill it with the maximum possible and provide information to the user
    if (amountApplied.signum() == 0 && useHighestAmount.equals("Y")) {
        amountApplied = newPaymentApplyAvailable;
        if (invoiceId != null && newInvoiceApplyAvailable.compareTo(amountApplied) < 0) {
            amountApplied = newInvoiceApplyAvailable;
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToInvoice",
                    UtilMisc.toMap("invoiceId", invoiceId), locale);
        }
        if (toPaymentId != null && newToPaymentApplyAvailable.compareTo(amountApplied) < 0) {
            amountApplied = newToPaymentApplyAvailable;
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToPayment",
                    UtilMisc.toMap("paymentId", toPaymentId), locale);
        }
    }

    String successMessage = null;
    if (amountApplied.signum() == 0) {
        errorMessageList.add(UtilProperties.getMessage(resource, "AccountingNoAmount", locale));
    } else {
        successMessage = UtilProperties.getMessage(resource, "AccountingApplicationSuccess",
                UtilMisc.<String, Object>toMap("amountApplied", amountApplied, "paymentId", paymentId,
                        "isoCode", currencyUomId, "toMessage", toMessage),
                locale);
    }
    // report error messages if any
    if (errorMessageList.size() > 0) {
        return ServiceUtil.returnError(errorMessageList);
    }

    // ============ start processing ======================
    // if the application is specified it is easy, update the existing record only
    if (paymentApplicationId != null) {
        // record is already retrieved previously
        if (debug)
            Debug.logInfo("Process an existing paymentApplication record: " + paymentApplicationId, module);
        // update the current record
        paymentApplication.set("invoiceId", invoiceId);
        paymentApplication.set("invoiceItemSeqId", invoiceItemSeqId);
        paymentApplication.set("paymentId", paymentId);
        paymentApplication.set("toPaymentId", toPaymentId);
        paymentApplication.set("amountApplied", amountApplied);
        paymentApplication.set("billingAccountId", billingAccountId);
        paymentApplication.set("taxAuthGeoId", taxAuthGeoId);
        return storePaymentApplication(delegator, paymentApplication, locale);
    }

    // if no invoice sequence number is provided it assumed the requested paymentAmount will be
    // spread over the invoice starting with the lowest sequence number if
    // itemprocessing is on otherwise create one record
    if (invoiceId != null && paymentId != null && (invoiceItemSeqId == null)) {
        if (invoiceProcessing) {
            // create only a single record with a null seqId
            if (debug)
                Debug.logInfo("Try to allocate the payment to the invoice as a whole", module);
            paymentApplication.set("paymentId", paymentId);
            paymentApplication.set("toPaymentId", null);
            paymentApplication.set("invoiceId", invoiceId);
            paymentApplication.set("invoiceItemSeqId", null);
            paymentApplication.set("toPaymentId", null);
            paymentApplication.set("amountApplied", amountApplied);
            paymentApplication.set("billingAccountId", billingAccountId);
            paymentApplication.set("taxAuthGeoId", null);
            if (debug)
                Debug.logInfo("creating new paymentapplication", module);
            return storePaymentApplication(delegator, paymentApplication, locale);
        } else { // spread the amount over every single item number
            if (debug)
                Debug.logInfo("Try to allocate the payment to the itemnumbers of the invoice", module);
            // get the invoice items
            List<GenericValue> invoiceItems = null;
            try {
                invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", invoiceId)
                        .queryList();
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
            if (invoiceItems.size() == 0) {
                errorMessageList
                        .add(UtilProperties.getMessage(resource, "AccountingNoInvoiceItemsFoundForInvoice",
                                UtilMisc.toMap("invoiceId", invoiceId), locale));
                return ServiceUtil.returnError(errorMessageList);
            } else { // we found some invoice items, start processing....
                // check if the user want to apply a smaller amount than the maximum possible on the payment
                if (amountApplied.signum() != 0 && amountApplied.compareTo(paymentApplyAvailable) < 0) {
                    paymentApplyAvailable = amountApplied;
                }
                for (GenericValue currentInvoiceItem : invoiceItems) {
                    if (paymentApplyAvailable.compareTo(ZERO) > 0) {
                        break;
                    }
                    if (debug)
                        Debug.logInfo(
                                "Start processing item: " + currentInvoiceItem.getString("invoiceItemSeqId"),
                                module);
                    BigDecimal itemQuantity = BigDecimal.ONE;
                    if (currentInvoiceItem.get("quantity") != null
                            && currentInvoiceItem.getBigDecimal("quantity").signum() != 0) {
                        itemQuantity = new BigDecimal(currentInvoiceItem.getString("quantity"))
                                .setScale(DECIMALS, ROUNDING);
                    }
                    BigDecimal itemAmount = currentInvoiceItem.getBigDecimal("amount").setScale(DECIMALS,
                            ROUNDING);
                    BigDecimal itemTotal = itemAmount.multiply(itemQuantity).setScale(DECIMALS, ROUNDING);

                    // get the application(s) already allocated to this
                    // item, if available
                    List<GenericValue> paymentApplications = null;
                    try {
                        paymentApplications = currentInvoiceItem.getRelated("PaymentApplication", null, null,
                                false);
                    } catch (GenericEntityException e) {
                        return ServiceUtil.returnError(e.getMessage());
                    }
                    BigDecimal tobeApplied = ZERO;
                    // item total amount - already applied (if any)
                    BigDecimal alreadyApplied = ZERO;
                    if (UtilValidate.isNotEmpty(paymentApplications)) {
                        // application(s) found, add them all together
                        Iterator<GenericValue> p = paymentApplications.iterator();
                        while (p.hasNext()) {
                            paymentApplication = p.next();
                            alreadyApplied = alreadyApplied.add(paymentApplication
                                    .getBigDecimal("amountApplied").setScale(DECIMALS, ROUNDING));
                        }
                        tobeApplied = itemTotal.subtract(alreadyApplied).setScale(DECIMALS, ROUNDING);
                    } else {
                        // no application connected yet
                        tobeApplied = itemTotal;
                    }
                    if (debug)
                        Debug.logInfo("tobeApplied:(" + tobeApplied + ") = " + "itemTotal(" + itemTotal
                                + ") - alreadyApplied(" + alreadyApplied
                                + ") but not more then (nonapplied) paymentAmount(" + paymentApplyAvailable
                                + ")", module);

                    if (tobeApplied.signum() == 0) {
                        // invoiceItem already fully applied so look at the next one....
                        continue;
                    }

                    if (paymentApplyAvailable.compareTo(tobeApplied) > 0) {
                        paymentApplyAvailable = paymentApplyAvailable.subtract(tobeApplied);
                    } else {
                        tobeApplied = paymentApplyAvailable;
                        paymentApplyAvailable = ZERO;
                    }

                    // create application payment record but check currency
                    // first if supplied
                    if (invoice.get("currencyUomId") != null && currencyUomId != null
                            && !invoice.getString("currencyUomId").equals(currencyUomId)) {
                        errorMessageList.add("Payment currency (" + currencyUomId + ") and invoice currency("
                                + invoice.getString("currencyUomId") + ") not the same\n");
                    } else {
                        paymentApplication.set("paymentApplicationId", null);
                        // make sure we get a new record
                        paymentApplication.set("invoiceId", invoiceId);
                        paymentApplication.set("invoiceItemSeqId",
                                currentInvoiceItem.getString("invoiceItemSeqId"));
                        paymentApplication.set("paymentId", paymentId);
                        paymentApplication.set("toPaymentId", toPaymentId);
                        paymentApplication.set("amountApplied", tobeApplied);
                        paymentApplication.set("billingAccountId", billingAccountId);
                        paymentApplication.set("taxAuthGeoId", taxAuthGeoId);
                        storePaymentApplication(delegator, paymentApplication, locale);
                    }

                    // check if either the invoice or the payment is fully
                    // applied, when yes change the status to paid
                    // which triggers the ledger routines....
                    /*
                     * if
                     * (InvoiceWorker.getInvoiceTotal(invoice).equals(InvoiceWorker.getInvoiceApplied(invoice))) {
                     * try { dispatcher.runSync("setInvoiceStatus",
                     * UtilMisc.toMap("invoiceId",invoiceId,"statusId","INVOICE_PAID")); }
                     * catch (GenericServiceException e1) {
                     * Debug.logError(e1, "Error updating invoice status",
                     * module); } }
                     *
                     * if
                     * (payment.getBigDecimal("amount").equals(PaymentWorker.getPaymentApplied(payment))) {
                     * GenericValue appliedPayment = (GenericValue)
                     * delegator.makeValue("Payment",
                     * UtilMisc.toMap("paymentId",paymentId,"statusId","INVOICE_PAID"));
                     * try { appliedPayment.store(); } catch
                     * (GenericEntityException e) {
                     * ServiceUtil.returnError(e.getMessage()); } }
                     */
                }

                if (errorMessageList.size() > 0) {
                    return ServiceUtil.returnError(errorMessageList);
                } else {
                    if (successMessage != null) {
                        return ServiceUtil.returnSuccess(successMessage);
                    } else {
                        return ServiceUtil.returnSuccess();
                    }
                }
            }
        }
    }

    // if no paymentApplicationId supplied create a new record with the data
    // supplied...
    if (paymentApplicationId == null && amountApplied != null) {
        paymentApplication.set("paymentApplicationId", paymentApplicationId);
        paymentApplication.set("invoiceId", invoiceId);
        paymentApplication.set("invoiceItemSeqId", invoiceItemSeqId);
        paymentApplication.set("paymentId", paymentId);
        paymentApplication.set("toPaymentId", toPaymentId);
        paymentApplication.set("amountApplied", amountApplied);
        paymentApplication.set("billingAccountId", billingAccountId);
        paymentApplication.set("taxAuthGeoId", taxAuthGeoId);
        return storePaymentApplication(delegator, paymentApplication, locale);
    }

    // should never come here...
    errorMessageList.add(
            UtilProperties.getMessage(resource, "AccountingPaymentApplicationParameterUnsuitable", locale));
    errorMessageList
            .add(UtilProperties.getMessage(resource, "AccountingPaymentApplicationParameterListUnsuitable",
                    UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId, "paymentId",
                            paymentId, "toPaymentId", toPaymentId, "paymentApplicationId", paymentApplicationId,
                            "amountApplied", amountApplied),
                    locale));
    return ServiceUtil.returnError(errorMessageList);
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String sendSiModBase() {
    String pagina = null;/*from  w  w w  . j  a  v  a2  s.  c  o  m*/
    try {

        if (StringUtils.isBlank(this.getSelectedBaseLegal().getVmsjmoderador())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                    "Campo requerido. Ingrese el mensaje a enviar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            pagina = null;
        } else {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User usuario = loginMB.getUser();
            if (this.getChkDestacado()) {
                ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
                HashMap filter = new HashMap();
                filter.put("ntipoconocimientoid", Constante.BASELEGAL);
                BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
                if (cant.intValue() >= 10) {
                    this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                    RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                    return "";
                }
            }
            if (this.getSelectedCategoria() != null) {
                this.getSelectedBaseLegal().setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
            }
            BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
            this.getSelectedBaseLegal()
                    .setVnombre(StringUtils.capitalize(this.getSelectedBaseLegal().getVnombre()));
            this.getSelectedBaseLegal().setVnumero(
                    this.getTipoNorma().concat(" - ").concat(StringUtils.upperCase(this.getNumeroNorma())));
            this.getSelectedBaseLegal().setNrangoid(this.getSelectedBaseLegal().getNrangoid());
            this.getSelectedBaseLegal()
                    .setNgobnacional(this.getChkGobNacional() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal()
                    .setNgobregional(this.getChkGobRegional() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal().setNgoblocal(this.getChkGobLocal() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal()
                    .setNmancomunidades(this.getChkMancomunidades() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal()
                    .setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal().setVsumilla(this.getSelectedBaseLegal().getVsumilla().trim());
            this.getSelectedBaseLegal()
                    .setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
            this.getSelectedBaseLegal().setVtema(this.getSelectedBaseLegal().getVtema());
            this.getSelectedBaseLegal().setVusuariomodificacion(usuario.getVlogin());
            this.getSelectedBaseLegal().setDfechamodificacion(new Date());
            this.getSelectedBaseLegal()
                    .setVmsjmoderador(this.getSelectedBaseLegal().getVmsjmoderador().toUpperCase());
            service.saveOrUpdate(this.getSelectedBaseLegal());

            BaseLegalHistorialService serviceHistorial = (BaseLegalHistorialService) ServiceFinder
                    .findBean("BaseLegalHistorialService");
            BaselegalHist hist = serviceHistorial
                    .getLastHistorialByBaselegal(this.getSelectedBaseLegal().getNbaselegalid());

            BaselegalHist baseHist = new BaselegalHist();
            baseHist.setNhistorialid(serviceHistorial.getNextPK());
            baseHist.setNbaselegalid(this.getSelectedBaseLegal().getNbaselegalid());
            baseHist.setNcategoriaid(this.getSelectedBaseLegal().getNcategoriaid());
            baseHist.setVnombre(this.getSelectedBaseLegal().getVnombre());
            baseHist.setVnumero(this.getSelectedBaseLegal().getVnumero());
            baseHist.setNrangoid(this.getSelectedBaseLegal().getNrangoid());
            baseHist.setNgobnacional(this.getSelectedBaseLegal().getNgobnacional());
            baseHist.setNgobregional(this.getSelectedBaseLegal().getNgobregional());
            baseHist.setNgoblocal(this.getSelectedBaseLegal().getNgoblocal());
            baseHist.setNmancomunidades(this.getSelectedBaseLegal().getNmancomunidades());
            baseHist.setNdestacado(this.getSelectedBaseLegal().getNdestacado());
            baseHist.setVsumilla(this.getSelectedBaseLegal().getVsumilla());
            baseHist.setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
            baseHist.setVtema(this.getSelectedBaseLegal().getVtema());
            baseHist.setNactivo(this.getSelectedBaseLegal().getNactivo());
            baseHist.setNestadoid(this.getSelectedBaseLegal().getNestadoid());
            baseHist.setNversion(BigDecimal.valueOf(hist.getNversion().intValue() + 1));
            baseHist.setVusuariocreacion(usuario.getVlogin());
            baseHist.setDfechacreacion(new Date());
            baseHist.setVusuariomodificacion(this.getSelectedBaseLegal().getVusuariomodificacion());
            baseHist.setDfechamodificacion(this.getSelectedBaseLegal().getDfechamodificacion());
            serviceHistorial.saveOrUpdate(baseHist);

            Tbaselegal tbaselegal = new Tbaselegal();
            BeanUtils.copyProperties(tbaselegal, this.getSelectedBaseLegal());

            String ruta0 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                    + BigDecimal.ZERO.toString() + "/";
            String ruta1 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                    + baseHist.getNversion().toString() + "/";

            ArchivoService aservice = (ArchivoService) ServiceFinder.findBean("ArchivoService");
            Archivo archivo = aservice.getArchivoByBaseLegal(this.getSelectedBaseLegal());
            if (this.getUploadFile() != null) {
                archivo.setVnombre(this.getUploadFile().getFileName());
                archivo.setVruta(ruta0 + archivo.getVnombre());
                archivo.setVusuariomodificacion(usuario.getVlogin());
                archivo.setDfechamodificacion(new Date());
                aservice.saveOrUpdate(archivo);
                saveFile(ruta0);
            }

            ArchivoHistorialService aserviceHist = (ArchivoHistorialService) ServiceFinder
                    .findBean("ArchivoHistorialService");
            ArchivoHist aHist = aserviceHist.getLastArchivoHistByBaseLegalHist(baseHist);

            ArchivoHist archivoHist = new ArchivoHist();
            archivoHist.setNarchivohistid(aserviceHist.getNextPK());
            archivoHist.setNhistorialid(baseHist.getNhistorialid());
            archivoHist.setNbaselegalid(baseHist.getNbaselegalid());
            archivoHist.setVnombre(archivo.getVnombre());
            archivoHist.setVruta(ruta1 + archivo.getVnombre());
            archivoHist.setVusuariocreacion(usuario.getVlogin());
            archivoHist.setDfechacreacion(new Date());
            aserviceHist.saveOrUpdate(archivoHist);
            saveFile(ruta1);

            VinculoBaseLegalService vservice = (VinculoBaseLegalService) ServiceFinder
                    .findBean("VinculoBaseLegalService");
            vservice.deleteByBaseLegal(this.getSelectedBaseLegal());
            for (BaseLegal v : this.getListaTarget()) {
                TvinculoBaselegalId id = new TvinculoBaselegalId();
                id.setNbaselegalid(tbaselegal.getNbaselegalid());
                id.setNvinculoid(vservice.getNextPK());
                VinculoBaselegal vinculo = new VinculoBaselegal();
                vinculo.setId(id);
                vinculo.setTbaselegal(tbaselegal);
                vinculo.setNbaselegalvinculadaid(v.getNbaselegalid());
                vinculo.setNtipovinculo(v.getNestadoid());
                vinculo.setDfechacreacion(new Date());
                vinculo.setVusuariocreacion(usuario.getVlogin());
                vservice.saveOrUpdate(vinculo);

                BaseLegal blvinculada = service.getBaselegalById(v.getNbaselegalid());
                blvinculada.setNestadoid(v.getNestadoid());
                blvinculada.setDfechamodificacion(new Date());
                blvinculada.setVusuariomodificacion(usuario.getVlogin());
                service.saveOrUpdate(blvinculada);

                if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_MODIFICADA)
                        || v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_CONCORDADO)) {

                    ConocimientoService cservice = (ConocimientoService) ServiceFinder
                            .findBean("ConocimientoService");
                    List<Consulta> listaConocimientos = cservice
                            .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                    for (Consulta c : listaConocimientos) {
                        Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                        conocimiento.setDfechamodificacion(new Date());
                        conocimiento.setVusuariomodificacion(usuario.getVlogin());
                        String descHtml = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                                "html.txt");
                        String descPlain = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                                "plain.txt");
                        cservice.saveOrUpdate(conocimiento);

                        HistorialService historialService = (HistorialService) ServiceFinder
                                .findBean("HistorialService");
                        Historial lastHistorial = historialService
                                .getLastHistorialByConocimiento(conocimiento.getNconocimientoid());
                        int lastversion;
                        if (lastHistorial != null) {
                            lastversion = lastHistorial.getNnumversion().intValue();
                        } else {
                            lastversion = 0;
                        }
                        String newpath = "";
                        if (conocimiento.getNtipoconocimientoid().equals(Constante.BASELEGAL)) {
                            newpath = "bl/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.BUENAPRACTICA)) {
                            newpath = "bp/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.CONTENIDO)) {
                            newpath = "ct/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.OPORTUNIDADMEJORA)) {
                            newpath = "om/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.PREGUNTAS)) {
                            newpath = "pr/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.WIKI)) {
                            newpath = "wk/";
                        }

                        String url = newpath.concat(conocimiento.getNconocimientoid().toString()).concat("/")
                                .concat(Integer.toString(lastversion + 1)).concat("/");

                        ThistorialId thistorialId = new ThistorialId();
                        thistorialId.setNconocimientoid(conocimiento.getNconocimientoid());
                        thistorialId.setNhistorialid(historialService.getNextPK());
                        Historial historial = new Historial();
                        historial.setId(thistorialId);
                        historial.setNtipoconocimientoid(conocimiento.getNtipoconocimientoid());
                        historial.setNcategoriaid(conocimiento.getNcategoriaid());
                        historial.setVtitulo(conocimiento.getVtitulo());
                        historial.setNactivo(BigDecimal.ONE);
                        historial.setNsituacionid(conocimiento.getNsituacionid());
                        historial.setVruta(url);
                        historial.setNnumversion(BigDecimal.valueOf(lastversion + 1));
                        historial.setDfechacreacion(new Date());
                        historial.setVusuariocreacion(usuario.getVlogin());
                        historialService.saveOrUpdate(historial);

                        GcmFileUtils.writeStringToFileServer(url, "html.txt", descHtml);
                        GcmFileUtils.writeStringToFileServer(url, "plain.txt", descPlain);

                        SeccionService seccionService = (SeccionService) ServiceFinder
                                .findBean("SeccionService");
                        SeccionHistService seccionHistService = (SeccionHistService) ServiceFinder
                                .findBean("SeccionHistService");
                        List<Seccion> listaSecc = seccionService
                                .getSeccionesByConocimiento(conocimiento.getNconocimientoid());
                        if (!CollectionUtils.isEmpty(listaSecc)) {
                            String url0 = conocimiento.getVruta().concat("s");
                            String url1 = url.concat("s");
                            for (Seccion seccion : listaSecc) {
                                seccion.setDetalleHtml(
                                        GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                                ruta0 = url0.concat(seccion.getNorden().toString()).concat("/");
                                seccion.setVruta(ruta0);
                                seccion.setDfechamodificacion(new Date());
                                seccion.setVusuariomodificacion(usuario.getVlogin());
                                seccionService.saveOrUpdate(seccion);

                                seccion.setDetallePlain(Jsoup.parse(seccion.getDetalleHtml()).text());

                                ruta1 = url1.concat(seccion.getNorden().toString()).concat("/");
                                TseccionHistId tseccionHistId = new TseccionHistId();
                                tseccionHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                                tseccionHistId.setNhistorialid(thistorialId.getNhistorialid());
                                tseccionHistId.setNseccionhid(seccionHistService.getNextPK());
                                SeccionHist seccionHist = new SeccionHist();
                                seccionHist.setId(tseccionHistId);
                                seccionHist.setNorden(seccion.getNorden());
                                seccionHist.setVruta(ruta1);
                                seccionHist.setVtitulo(seccion.getVtitulo());
                                seccionHist.setVusuariocreacion(usuario.getVlogin());
                                seccionHist.setDfechacreacion(new Date());
                                seccionHistService.saveOrUpdate(seccionHist);

                                GcmFileUtils.writeStringToFileServer(ruta1, "html.txt",
                                        seccion.getDetalleHtml());
                                GcmFileUtils.writeStringToFileServer(ruta1, "plain.txt",
                                        seccion.getDetallePlain());
                            }
                        }

                        VinculoService vinculoService = (VinculoService) ServiceFinder
                                .findBean("VinculoService");
                        Vinculo vinculoC = new Vinculo();
                        vinculoC.setNvinculoid(vinculoService.getNextPK());
                        vinculoC.setNconocimientoid(conocimiento.getNconocimientoid());
                        vinculoC.setNconocimientovinc(tbaselegal.getNbaselegalid());
                        vinculoC.setNtipoconocimientovinc(Constante.BASELEGAL);
                        vinculoC.setDfechacreacion(new Date());
                        vinculoC.setVusuariocreacion(usuario.getVlogin());
                        vinculoService.saveOrUpdate(vinculoC);

                        List<Vinculo> vinculos = vinculoService
                                .getVinculosByConocimiento(conocimiento.getNtipoconocimientoid());
                        VinculoHistService vinculoHistService = (VinculoHistService) ServiceFinder
                                .findBean("VinculoHistService");
                        for (Vinculo vinc : vinculos) {
                            TvinculoHistId vinculoHistId = new TvinculoHistId();
                            vinculoHistId.setNvinculohid(vinculoHistService.getNextPK());
                            vinculoHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                            vinculoHistId.setNhistorialid(thistorialId.getNhistorialid());
                            VinculoHist vinculoHist = new VinculoHist();
                            vinculoHist.setId(vinculoHistId);
                            vinculoHist.setNconocimientovinc(vinc.getNconocimientovinc());
                            vinculoHist.setDfechacreacion(new Date());
                            vinculoHist.setVusuariocreacion(usuario.getVlogin());
                            vinculoHistService.saveOrUpdate(vinculoHist);
                        }
                    }
                } else if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_DEROGADA)) {
                    ConocimientoService cservice = (ConocimientoService) ServiceFinder
                            .findBean("ConocimientoService");
                    List<Consulta> listaConocimientos = cservice
                            .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                    for (Consulta c : listaConocimientos) {
                        Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                        conocimiento.setNflgvinculo(BigDecimal.ONE);
                        conocimiento.setDfechamodificacion(new Date());
                        conocimiento.setVusuariomodificacion(usuario.getVlogin());
                    }
                }

                VinculoBaselegalHistorialService vserviceHist = (VinculoBaselegalHistorialService) ServiceFinder
                        .findBean("VinculoBaselegalHistorialService");
                VinculoBaselegalHist vinculoHist = new VinculoBaselegalHist();
                vinculoHist.setNvinculohistid(vserviceHist.getNextPK());
                vinculoHist.setNhistorialid(baseHist.getNhistorialid());
                vinculoHist.setNbaselegalid(baseHist.getNbaselegalid());
                vinculoHist.setNbaselegalvinculadaid(v.getNbaselegalid());
                vinculoHist.setNtipovinculo(v.getNestadoid());
                vinculoHist.setDfechacreacion(new Date());
                vinculoHist.setVusuariocreacion(usuario.getVlogin());
                vserviceHist.saveOrUpdate(vinculoHist);
            }

            AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
            this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            this.getSelectedAsignacion().setDfechaatencion(new Date());
            this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("9")));
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            Asignacion asignacion = new Asignacion();
            asignacion.setNasignacionid(serviceasig.getNextPK());
            asignacion.setNtipoconocimientoid(Constante.BASELEGAL);
            asignacion.setNconocimientoid(this.getSelectedBaseLegal().getNbaselegalid());
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("1")));
            asignacion.setNusuarioid(
                    serviceasig.getUserCreacionByBaseLegal(this.getSelectedBaseLegal().getNbaselegalid()));
            asignacion.setDfechaasignacion(new Date());
            asignacion.setDfechacreacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            loginMB.refreshNotifications();

            pagina = "/index.xhtml";
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return pagina;
}

From source file:org.apache.ofbiz.accounting.invoice.InvoiceServices.java

public static Map<String, Object> updatePaymentApplicationDefBd(DispatchContext dctx,
        Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    if (DECIMALS == -1 || ROUNDING == -1) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resource, "AccountingAritmeticPropertiesNotConfigured", locale));
    }// w  ww.ja  v a  2 s  .  c  o m

    if (!context.containsKey("useHighestAmount")) {
        context.put("useHighestAmount", "Y");
    }

    String defaultInvoiceProcessing = EntityUtilProperties.getPropertyValue("accounting", "invoiceProcessing",
            delegator);

    boolean debug = true; // show processing messages in the log..or not....

    // a 'y' in invoiceProssesing will reverse the default processing
    String changeProcessing = (String) context.get("invoiceProcessing");
    String invoiceId = (String) context.get("invoiceId");
    String invoiceItemSeqId = (String) context.get("invoiceItemSeqId");
    String paymentId = (String) context.get("paymentId");
    String toPaymentId = (String) context.get("toPaymentId");
    String paymentApplicationId = (String) context.get("paymentApplicationId");
    BigDecimal amountApplied = (BigDecimal) context.get("amountApplied");
    String billingAccountId = (String) context.get("billingAccountId");
    String taxAuthGeoId = (String) context.get("taxAuthGeoId");
    String useHighestAmount = (String) context.get("useHighestAmount");

    List<String> errorMessageList = new LinkedList<String>();

    if (debug)
        Debug.logInfo("updatePaymentApplicationDefBd input parameters..." + " defaultInvoiceProcessing: "
                + defaultInvoiceProcessing + " changeDefaultInvoiceProcessing: " + changeProcessing
                + " useHighestAmount: " + useHighestAmount + " paymentApplicationId: " + paymentApplicationId
                + " PaymentId: " + paymentId + " InvoiceId: " + invoiceId + " InvoiceItemSeqId: "
                + invoiceItemSeqId + " BillingAccountId: " + billingAccountId + " toPaymentId: " + toPaymentId
                + " amountApplied: " + amountApplied + " TaxAuthGeoId: " + taxAuthGeoId, module);

    if (changeProcessing == null) {
        changeProcessing = "N"; // not provided, so no change
    }

    boolean invoiceProcessing = true;
    if (defaultInvoiceProcessing.equals("YY")) {
        invoiceProcessing = true;
    } else if (defaultInvoiceProcessing.equals("NN")) {
        invoiceProcessing = false;
    } else if (defaultInvoiceProcessing.equals("Y")) {
        invoiceProcessing = !"Y".equals(changeProcessing);
    } else if (defaultInvoiceProcessing.equals("N")) {
        invoiceProcessing = "Y".equals(changeProcessing);
    }

    // on a new paymentApplication check if only billing or invoice or tax
    // id is provided not 2,3... BUT a combination of billingAccountId and invoiceId is permitted - that's how you use a
    // Billing Account to pay for an Invoice
    if (paymentApplicationId == null) {
        int count = 0;
        if (invoiceId != null)
            count++;
        if (toPaymentId != null)
            count++;
        if (billingAccountId != null)
            count++;
        if (taxAuthGeoId != null)
            count++;
        if ((billingAccountId != null) && (invoiceId != null))
            count--;
        if (count != 1) {
            errorMessageList.add(UtilProperties.getMessage(resource,
                    "AccountingSpecifyInvoiceToPaymentBillingAccountTaxGeoId", locale));
        }
    }

    // avoid null pointer exceptions.
    if (amountApplied == null)
        amountApplied = ZERO;
    // makes no sense to have an item numer without an invoice number
    if (invoiceId == null)
        invoiceItemSeqId = null;

    // retrieve all information and perform checking on the retrieved info.....

    // Payment.....
    BigDecimal paymentApplyAvailable = ZERO;
    // amount available on the payment reduced by the already applied amounts
    BigDecimal amountAppliedMax = ZERO;
    // the maximum that can be applied taking payment,invoice,invoiceitem,billing account in concideration
    // if maxApplied is missing, this value can be used,
    // Payment this should be checked after the invoice checking because it is possible the currency is changed
    GenericValue payment = null;
    String currencyUomId = null;
    if (paymentId == null || paymentId.equals("")) {
        errorMessageList
                .add(UtilProperties.getMessage(resource, "AccountingPaymentIdBlankNotSupplied", locale));
    } else {
        try {
            payment = EntityQuery.use(delegator).from("Payment").where("paymentId", paymentId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (payment == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentRecordNotFound",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }
        paymentApplyAvailable = payment.getBigDecimal("amount")
                .subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING);

        if (payment.getString("statusId").equals("PMNT_CANCELLED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentCancelled",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }
        if (payment.getString("statusId").equals("PMNT_CONFIRMED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentConfirmed",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }

        currencyUomId = payment.getString("currencyUomId");

        // if the amount to apply is 0 give it amount the payment still need
        // to apply
        if (amountApplied.signum() == 0) {
            amountAppliedMax = paymentApplyAvailable;
        }

    }

    // the "TO" Payment.....
    BigDecimal toPaymentApplyAvailable = ZERO;
    GenericValue toPayment = null;
    if (toPaymentId != null && !toPaymentId.equals("")) {
        try {
            toPayment = EntityQuery.use(delegator).from("Payment").where("paymentId", toPaymentId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (toPayment == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentRecordNotFound",
                    UtilMisc.toMap("paymentId", toPaymentId), locale));
        }
        toPaymentApplyAvailable = toPayment.getBigDecimal("amount")
                .subtract(PaymentWorker.getPaymentApplied(toPayment)).setScale(DECIMALS, ROUNDING);

        if (toPayment.getString("statusId").equals("PMNT_CANCELLED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentCancelled",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }
        if (toPayment.getString("statusId").equals("PMNT_CONFIRMED")) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentConfirmed",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        }

        // if the amount to apply is less then required by the payment reduce it
        if (amountAppliedMax.compareTo(toPaymentApplyAvailable) > 0) {
            amountAppliedMax = toPaymentApplyAvailable;
        }

        if (paymentApplicationId == null) {
            // only check for new application records, update on existing records is checked in the paymentApplication section
            if (toPaymentApplyAvailable.signum() == 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentAlreadyApplied",
                        UtilMisc.toMap("paymentId", toPaymentId), locale));
            } else {
                // check here for too much application if a new record is
                // added (paymentApplicationId == null)
                if (amountApplied.compareTo(toPaymentApplyAvailable) > 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentLessRequested",
                            UtilMisc.<String, Object>toMap("paymentId", toPaymentId, "paymentApplyAvailable",
                                    toPaymentApplyAvailable, "amountApplied", amountApplied, "isoCode",
                                    currencyUomId),
                            locale));
                }
            }
        }

        // check if at least one send is the same as one receiver on the other payment
        if (!payment.getString("partyIdFrom").equals(toPayment.getString("partyIdTo"))
                && !payment.getString("partyIdTo").equals(toPayment.getString("partyIdFrom"))) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingFromPartySameToParty", locale));
        }

        if (debug)
            Debug.logInfo("toPayment info retrieved and checked...", module);
    }

    // assign payment to billing account if the invoice is assigned to this billing account
    if (invoiceId != null) {
        GenericValue invoice = null;
        try {
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", invoiceId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }

        if (invoice == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceNotFound",
                    UtilMisc.toMap("invoiceId", invoiceId), locale));
        } else {
            if (invoice.getString("billingAccountId") != null) {
                billingAccountId = invoice.getString("billingAccountId");
            }
        }
    }

    // billing account
    GenericValue billingAccount = null;
    if (billingAccountId != null && !billingAccountId.equals("")) {
        try {
            billingAccount = EntityQuery.use(delegator).from("BillingAccount")
                    .where("billingAccountId", billingAccountId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (billingAccount == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingBillingAccountNotFound",
                    UtilMisc.toMap("billingAccountId", billingAccountId), locale));
        }
        // check the currency
        if (billingAccount.get("accountCurrencyUomId") != null && currencyUomId != null
                && !billingAccount.getString("accountCurrencyUomId").equals(currencyUomId)) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingBillingAccountCurrencyProblem",
                    UtilMisc.toMap("billingAccountId", billingAccountId, "accountCurrencyUomId",
                            billingAccount.getString("accountCurrencyUomId"), "paymentId", paymentId,
                            "paymentCurrencyUomId", currencyUomId),
                    locale));
        }

        if (debug)
            Debug.logInfo("Billing Account info retrieved and checked...", module);
    }

    // get the invoice (item) information
    BigDecimal invoiceApplyAvailable = ZERO;
    // amount available on the invoice reduced by the already applied amounts
    BigDecimal invoiceItemApplyAvailable = ZERO;
    // amount available on the invoiceItem reduced by the already applied amounts
    GenericValue invoice = null;
    GenericValue invoiceItem = null;
    if (invoiceId != null) {
        try {
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", invoiceId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }

        if (invoice == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceNotFound",
                    UtilMisc.toMap("invoiceId", invoiceId), locale));
        } else { // check the invoice and when supplied the invoice item...

            if (invoice.getString("statusId").equals("INVOICE_CANCELLED")) {
                errorMessageList
                        .add(UtilProperties.getMessage(resource, "AccountingInvoiceCancelledCannotApplyTo",
                                UtilMisc.toMap("invoiceId", invoiceId), locale));
            }

            // check the currency
            if (currencyUomId != null && invoice.get("currencyUomId") != null
                    && !currencyUomId.equals(invoice.getString("currencyUomId"))) {
                Debug.logInfo(
                        UtilProperties.getMessage(resource, "AccountingInvoicePaymentCurrencyProblem",
                                UtilMisc.toMap("invoiceCurrency", invoice.getString("currencyUomId"),
                                        "paymentCurrency", payment.getString("currencyUomId")),
                                locale),
                        module);
                Debug.logInfo("will try to apply payment on the actualCurrency amount on payment", module);

                if (payment.get("actualCurrencyAmount") == null || payment.get("actualCurrencyUomId") == null) {
                    errorMessageList.add(
                            "Actual amounts are required in the currency of the invoice to make this work....");
                } else {
                    currencyUomId = payment.getString("actualCurrencyUomId");
                    if (!currencyUomId.equals(invoice.getString("currencyUomId"))) {
                        errorMessageList.add("actual currency on payment (" + currencyUomId
                                + ") not the same as original invoice currency ("
                                + invoice.getString("currencyUomId") + ")");
                    }
                }
                paymentApplyAvailable = payment.getBigDecimal("actualCurrencyAmount")
                        .subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING);
                if (amountApplied.signum() == 0) {
                    amountAppliedMax = paymentApplyAvailable;
                }
            }

            // check if the invoice already covered by payments
            BigDecimal invoiceTotal = InvoiceWorker.getInvoiceTotal(invoice);
            invoiceApplyAvailable = InvoiceWorker.getInvoiceNotApplied(invoice);

            // adjust the amountAppliedMax value if required....
            if (invoiceApplyAvailable.compareTo(amountAppliedMax) < 0) {
                amountAppliedMax = invoiceApplyAvailable;
            }

            if (invoiceTotal.signum() == 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceTotalZero",
                        UtilMisc.toMap("invoiceId", invoiceId), locale));
            } else if (paymentApplicationId == null) {
                // only check for new records here...updates are checked in the paymentApplication section
                if (invoiceApplyAvailable.signum() == 0) {
                    errorMessageList
                            .add(UtilProperties.getMessage(resource, "AccountingInvoiceCompletelyApplied",
                                    UtilMisc.toMap("invoiceId", invoiceId), locale));
                }
                // check here for too much application if a new record(s) are
                // added (paymentApplicationId == null)
                else if (amountApplied.compareTo(invoiceApplyAvailable) > 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceLessRequested",
                            UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "invoiceApplyAvailable",
                                    invoiceApplyAvailable, "amountApplied", amountApplied, "isoCode",
                                    invoice.getString("currencyUomId")),
                            locale));
                }
            }

            // check if at least one sender is the same as one receiver on the invoice
            if (!payment.getString("partyIdFrom").equals(invoice.getString("partyId"))
                    && !payment.getString("partyIdTo").equals(invoice.getString("partyIdFrom"))) {
                errorMessageList
                        .add(UtilProperties.getMessage(resource, "AccountingFromPartySameToParty", locale));
            }

            if (debug)
                Debug.logInfo("Invoice info retrieved and checked ...", module);
        }

        // if provided check the invoice item.
        if (invoiceItemSeqId != null) {
            // when itemSeqNr not provided delay checking on invoiceItemSeqId
            try {
                invoiceItem = EntityQuery.use(delegator).from("InvoiceItem")
                        .where("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId).queryOne();
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(e.getMessage());
            }

            if (invoiceItem == null) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceItemNotFound",
                        UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId), locale));
            } else {
                if (invoice.get("currencyUomId") != null && currencyUomId != null
                        && !invoice.getString("currencyUomId").equals(currencyUomId)) {
                    errorMessageList.add(UtilProperties.getMessage(resource,
                            "AccountingInvoicePaymentCurrencyProblem", UtilMisc.toMap("paymentCurrencyId",
                                    currencyUomId, "itemCurrency", invoice.getString("currencyUomId")),
                            locale));
                }

                // get the invoice item applied value
                BigDecimal quantity = null;
                if (invoiceItem.get("quantity") == null) {
                    quantity = BigDecimal.ONE;
                } else {
                    quantity = invoiceItem.getBigDecimal("quantity").setScale(DECIMALS, ROUNDING);
                }
                invoiceItemApplyAvailable = invoiceItem.getBigDecimal("amount").multiply(quantity)
                        .setScale(DECIMALS, ROUNDING)
                        .subtract(InvoiceWorker.getInvoiceItemApplied(invoiceItem));
                // check here for too much application if a new record is added
                if (paymentApplicationId == null && amountApplied.compareTo(invoiceItemApplyAvailable) > 0) {
                    // new record
                    errorMessageList.add("Invoice(" + invoiceId + ") item(" + invoiceItemSeqId + ") has  "
                            + invoiceItemApplyAvailable + " to apply but " + amountApplied + " is requested\n");
                    String uomId = invoice.getString("currencyUomId");
                    errorMessageList.add(UtilProperties.getMessage(resource,
                            "AccountingInvoiceItemLessRequested",
                            UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "invoiceItemSeqId",
                                    invoiceItemSeqId, "invoiceItemApplyAvailable", invoiceItemApplyAvailable,
                                    "amountApplied", amountApplied, "isoCode", uomId),
                            locale));
                }
            }
            if (debug)
                Debug.logInfo(
                        "InvoiceItem info retrieved and checked against the Invoice (currency and amounts) ...",
                        module);
        }
    }

    // check this at the end because the invoice can change the currency.......
    if (paymentApplicationId == null) {
        // only check for new application records, update on existing records is checked in the paymentApplication section
        if (paymentApplyAvailable.signum() == 0) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentAlreadyApplied",
                    UtilMisc.toMap("paymentId", paymentId), locale));
        } else {
            // check here for too much application if a new record is
            // added (paymentApplicationId == null)
            if (amountApplied.compareTo(paymentApplyAvailable) > 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentLessRequested",
                        UtilMisc.<String, Object>toMap("paymentId", paymentId, "paymentApplyAvailable",
                                paymentApplyAvailable, "amountApplied", amountApplied, "isoCode",
                                currencyUomId),
                        locale));
            }
        }
    }

    // get the application record if the applicationId is supplied if not
    // create empty record.
    BigDecimal newInvoiceApplyAvailable = invoiceApplyAvailable;
    // amount available on the invoice taking into account if the invoiceItemnumber has changed
    BigDecimal newInvoiceItemApplyAvailable = invoiceItemApplyAvailable;
    // amount available on the invoiceItem taking into account if the itemnumber has changed
    BigDecimal newToPaymentApplyAvailable = toPaymentApplyAvailable;
    BigDecimal newPaymentApplyAvailable = paymentApplyAvailable;
    GenericValue paymentApplication = null;
    if (paymentApplicationId == null) {
        paymentApplication = delegator.makeValue("PaymentApplication");
        // prepare for creation
    } else { // retrieve existing paymentApplication
        try {
            paymentApplication = EntityQuery.use(delegator).from("PaymentApplication")
                    .where("paymentApplicationId", paymentApplicationId).queryOne();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }

        if (paymentApplication == null) {
            errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentApplicationNotFound",
                    UtilMisc.toMap("paymentApplicationId", paymentApplicationId), locale));
            paymentApplicationId = null;
        } else {

            // if both invoiceId and BillingId is entered there was
            // obviously a change
            // only take the newly entered item, same for tax authority and toPayment
            if (paymentApplication.get("invoiceId") == null && invoiceId != null) {
                billingAccountId = null;
                taxAuthGeoId = null;
                toPaymentId = null;
            } else if (paymentApplication.get("toPaymentId") == null && toPaymentId != null) {
                invoiceId = null;
                invoiceItemSeqId = null;
                taxAuthGeoId = null;
                billingAccountId = null;
            } else if (paymentApplication.get("billingAccountId") == null && billingAccountId != null) {
                invoiceId = null;
                invoiceItemSeqId = null;
                toPaymentId = null;
                taxAuthGeoId = null;
            } else if (paymentApplication.get("taxAuthGeoId") == null && taxAuthGeoId != null) {
                invoiceId = null;
                invoiceItemSeqId = null;
                toPaymentId = null;
                billingAccountId = null;
            }

            // check if the payment for too much application if an existing
            // application record is changed
            if (paymentApplyAvailable.compareTo(ZERO) == 0) {
                newPaymentApplyAvailable = paymentApplyAvailable
                        .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                        .setScale(DECIMALS, ROUNDING);
            } else {
                newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplyAvailable)
                        .subtract(amountApplied).setScale(DECIMALS, ROUNDING);
            }
            if (newPaymentApplyAvailable.compareTo(ZERO) < 0) {
                errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentNotEnough",
                        UtilMisc.<String, Object>toMap("paymentId", paymentId, "paymentApplyAvailable",
                                paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")),
                                "amountApplied", amountApplied),
                        locale));
            }

            if (invoiceId != null) {
                // only when we are processing an invoice on existing paymentApplication check invoice item for to much application if the invoice
                // number did not change
                if (invoiceId.equals(paymentApplication.getString("invoiceId"))) {
                    // check if both the itemNumbers are null then this is a
                    // record for the whole invoice
                    if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") == null) {
                        newInvoiceApplyAvailable = invoiceApplyAvailable
                                .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (invoiceApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList.add(UtilProperties.getMessage(resource,
                                    "AccountingInvoiceNotEnough", UtilMisc.<String, Object>toMap("tooMuch",
                                            newInvoiceApplyAvailable.negate(), "invoiceId", invoiceId),
                                    locale));
                        }
                    } else if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") != null) {
                        // check if the item number changed from a real Item number to a null value
                        newInvoiceApplyAvailable = invoiceApplyAvailable
                                .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (invoiceApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList.add(UtilProperties.getMessage(resource,
                                    "AccountingInvoiceNotEnough", UtilMisc.<String, Object>toMap("tooMuch",
                                            newInvoiceApplyAvailable.negate(), "invoiceId", invoiceId),
                                    locale));
                        }
                    } else if (invoiceItemSeqId != null && paymentApplication.get("invoiceItemSeqId") == null) {
                        // check if the item number changed from a null value to
                        // a real Item number
                        newInvoiceItemApplyAvailable = invoiceItemApplyAvailable.subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (newInvoiceItemApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList
                                    .add(UtilProperties.getMessage(resource, "AccountingItemInvoiceNotEnough",
                                            UtilMisc.<String, Object>toMap("tooMuch",
                                                    newInvoiceItemApplyAvailable.negate(), "invoiceId",
                                                    invoiceId, "invoiceItemSeqId", invoiceItemSeqId),
                                            locale));
                        }
                    } else if (invoiceItemSeqId.equals(paymentApplication.getString("invoiceItemSeqId"))) {
                        // check if the real item numbers the same
                        // item number the same numeric value
                        newInvoiceItemApplyAvailable = invoiceItemApplyAvailable
                                .add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (newInvoiceItemApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList
                                    .add(UtilProperties.getMessage(resource, "AccountingItemInvoiceNotEnough",
                                            UtilMisc.<String, Object>toMap("tooMuch",
                                                    newInvoiceItemApplyAvailable.negate(), "invoiceId",
                                                    invoiceId, "invoiceItemSeqId", invoiceItemSeqId),
                                            locale));
                        }
                    } else {
                        // item number changed only check new item
                        newInvoiceItemApplyAvailable = invoiceItemApplyAvailable.add(amountApplied)
                                .setScale(DECIMALS, ROUNDING);
                        if (newInvoiceItemApplyAvailable.compareTo(ZERO) < 0) {
                            errorMessageList
                                    .add(UtilProperties.getMessage(resource, "AccountingItemInvoiceNotEnough",
                                            UtilMisc.<String, Object>toMap("tooMuch",
                                                    newInvoiceItemApplyAvailable.negate(), "invoiceId",
                                                    invoiceId, "invoiceItemSeqId", invoiceItemSeqId),
                                            locale));
                        }
                    }

                    // if the amountApplied = 0 give it the higest possible
                    // value
                    if (amountApplied.signum() == 0) {
                        if (newInvoiceItemApplyAvailable.compareTo(newPaymentApplyAvailable) < 0) {
                            amountApplied = newInvoiceItemApplyAvailable;
                            // from the item number
                        } else {
                            amountApplied = newPaymentApplyAvailable;
                            // from the payment
                        }
                    }

                    // check the invoice
                    newInvoiceApplyAvailable = invoiceApplyAvailable
                            .add(paymentApplication.getBigDecimal("amountApplied").subtract(amountApplied))
                            .setScale(DECIMALS, ROUNDING);
                    if (newInvoiceApplyAvailable.compareTo(ZERO) < 0) {
                        errorMessageList.add(UtilProperties.getMessage(resource, "AccountingInvoiceNotEnough",
                                UtilMisc.<String, Object>toMap("tooMuch",
                                        invoiceApplyAvailable
                                                .add(paymentApplication.getBigDecimal("amountApplied"))
                                                .subtract(amountApplied),
                                        "invoiceId", invoiceId),
                                locale));
                    }
                }
            }

            // check the toPayment account when only the amountApplied has
            // changed,
            if (toPaymentId != null && toPaymentId.equals(paymentApplication.getString("toPaymentId"))) {
                newToPaymentApplyAvailable = toPaymentApplyAvailable
                        .subtract(paymentApplication.getBigDecimal("amountApplied")).add(amountApplied)
                        .setScale(DECIMALS, ROUNDING);
                if (newToPaymentApplyAvailable.compareTo(ZERO) < 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentNotEnough",
                            UtilMisc.<String, Object>toMap("paymentId", toPaymentId, "paymentApplyAvailable",
                                    newToPaymentApplyAvailable, "amountApplied", amountApplied),
                            locale));
                }
            } else if (toPaymentId != null) {
                // billing account entered number has changed so we have to
                // check the new billing account number.
                newToPaymentApplyAvailable = toPaymentApplyAvailable.add(amountApplied).setScale(DECIMALS,
                        ROUNDING);
                if (newToPaymentApplyAvailable.compareTo(ZERO) < 0) {
                    errorMessageList.add(UtilProperties.getMessage(resource, "AccountingPaymentNotEnough",
                            UtilMisc.<String, Object>toMap("paymentId", toPaymentId, "paymentApplyAvailable",
                                    newToPaymentApplyAvailable, "amountApplied", amountApplied),
                            locale));
                }

            }
        }
        if (debug)
            Debug.logInfo("paymentApplication record info retrieved and checked...", module);
    }

    // show the maximumus what can be added in the payment application file.
    String toMessage = null; // prepare for success message
    if (debug) {
        String extra = "";
        if (invoiceItemSeqId != null) {
            extra = " Invoice item(" + invoiceItemSeqId + ") amount not yet applied: "
                    + newInvoiceItemApplyAvailable;
        }
        Debug.logInfo("checking finished, start processing with the following data... ", module);
        if (invoiceId != null) {
            Debug.logInfo(" Invoice(" + invoiceId + ") amount not yet applied: " + newInvoiceApplyAvailable
                    + extra + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable
                    + " Requested amount to apply:" + amountApplied, module);
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToInvoice",
                    UtilMisc.toMap("invoiceId", invoiceId), locale);
            if (extra.length() > 0)
                toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToInvoiceItem",
                        UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId), locale);
        }
        if (toPaymentId != null) {
            Debug.logInfo(" toPayment(" + toPaymentId + ") amount not yet applied: "
                    + newToPaymentApplyAvailable + " Payment(" + paymentId + ") amount not yet applied: "
                    + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, module);
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToPayment",
                    UtilMisc.toMap("paymentId", toPaymentId), locale);
        }
        if (taxAuthGeoId != null) {
            Debug.logInfo(
                    " taxAuthGeoId(" + taxAuthGeoId + ")  Payment(" + paymentId + ") amount not yet applied: "
                            + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied,
                    module);
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToTax",
                    UtilMisc.toMap("taxAuthGeoId", taxAuthGeoId), locale);
        }
    }
    // if the amount to apply was not provided or was zero fill it with the maximum possible and provide information to the user
    if (amountApplied.signum() == 0 && useHighestAmount.equals("Y")) {
        amountApplied = newPaymentApplyAvailable;
        if (invoiceId != null && newInvoiceApplyAvailable.compareTo(amountApplied) < 0) {
            amountApplied = newInvoiceApplyAvailable;
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToInvoice",
                    UtilMisc.toMap("invoiceId", invoiceId), locale);
        }
        if (toPaymentId != null && newToPaymentApplyAvailable.compareTo(amountApplied) < 0) {
            amountApplied = newToPaymentApplyAvailable;
            toMessage = UtilProperties.getMessage(resource, "AccountingApplicationToPayment",
                    UtilMisc.toMap("paymentId", toPaymentId), locale);
        }
    }

    String successMessage = null;
    if (amountApplied.signum() == 0) {
        errorMessageList.add(UtilProperties.getMessage(resource, "AccountingNoAmount", locale));
    } else {
        successMessage = UtilProperties.getMessage(resource, "AccountingApplicationSuccess",
                UtilMisc.<String, Object>toMap("amountApplied", amountApplied, "paymentId", paymentId,
                        "isoCode", currencyUomId, "toMessage", toMessage),
                locale);
    }
    // report error messages if any
    if (errorMessageList.size() > 0) {
        return ServiceUtil.returnError(errorMessageList);
    }

    // ============ start processing ======================
    // if the application is specified it is easy, update the existing record only
    if (paymentApplicationId != null) {
        // record is already retrieved previously
        if (debug)
            Debug.logInfo("Process an existing paymentApplication record: " + paymentApplicationId, module);
        // update the current record
        paymentApplication.set("invoiceId", invoiceId);
        paymentApplication.set("invoiceItemSeqId", invoiceItemSeqId);
        paymentApplication.set("paymentId", paymentId);
        paymentApplication.set("toPaymentId", toPaymentId);
        paymentApplication.set("amountApplied", amountApplied);
        paymentApplication.set("billingAccountId", billingAccountId);
        paymentApplication.set("taxAuthGeoId", taxAuthGeoId);
        return storePaymentApplication(delegator, paymentApplication, locale);
    }

    // if no invoice sequence number is provided it assumed the requested paymentAmount will be
    // spread over the invoice starting with the lowest sequence number if
    // itemprocessing is on otherwise create one record
    if (invoiceId != null && paymentId != null && (invoiceItemSeqId == null)) {
        if (invoiceProcessing) {
            // create only a single record with a null seqId
            if (debug)
                Debug.logInfo("Try to allocate the payment to the invoice as a whole", module);
            paymentApplication.set("paymentId", paymentId);
            paymentApplication.set("toPaymentId", null);
            paymentApplication.set("invoiceId", invoiceId);
            paymentApplication.set("invoiceItemSeqId", null);
            paymentApplication.set("toPaymentId", null);
            paymentApplication.set("amountApplied", amountApplied);
            paymentApplication.set("billingAccountId", billingAccountId);
            paymentApplication.set("taxAuthGeoId", null);
            if (debug)
                Debug.logInfo("creating new paymentapplication", module);
            return storePaymentApplication(delegator, paymentApplication, locale);
        } else { // spread the amount over every single item number
            if (debug)
                Debug.logInfo("Try to allocate the payment to the itemnumbers of the invoice", module);
            // get the invoice items
            List<GenericValue> invoiceItems = null;
            try {
                invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", invoiceId)
                        .queryList();
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
            if (invoiceItems.size() == 0) {
                errorMessageList
                        .add(UtilProperties.getMessage(resource, "AccountingNoInvoiceItemsFoundForInvoice",
                                UtilMisc.toMap("invoiceId", invoiceId), locale));
                return ServiceUtil.returnError(errorMessageList);
            } else { // we found some invoice items, start processing....
                // check if the user want to apply a smaller amount than the maximum possible on the payment
                if (amountApplied.signum() != 0 && amountApplied.compareTo(paymentApplyAvailable) < 0) {
                    paymentApplyAvailable = amountApplied;
                }
                for (GenericValue currentInvoiceItem : invoiceItems) {
                    if (paymentApplyAvailable.compareTo(ZERO) > 0) {
                        break;
                    }
                    if (debug)
                        Debug.logInfo(
                                "Start processing item: " + currentInvoiceItem.getString("invoiceItemSeqId"),
                                module);
                    BigDecimal itemQuantity = BigDecimal.ONE;
                    if (currentInvoiceItem.get("quantity") != null
                            && currentInvoiceItem.getBigDecimal("quantity").signum() != 0) {
                        itemQuantity = new BigDecimal(currentInvoiceItem.getString("quantity"))
                                .setScale(DECIMALS, ROUNDING);
                    }
                    BigDecimal itemAmount = currentInvoiceItem.getBigDecimal("amount").setScale(DECIMALS,
                            ROUNDING);
                    BigDecimal itemTotal = itemAmount.multiply(itemQuantity).setScale(DECIMALS, ROUNDING);

                    // get the application(s) already allocated to this
                    // item, if available
                    List<GenericValue> paymentApplications = null;
                    try {
                        paymentApplications = currentInvoiceItem.getRelated("PaymentApplication", null, null,
                                false);
                    } catch (GenericEntityException e) {
                        return ServiceUtil.returnError(e.getMessage());
                    }
                    BigDecimal tobeApplied = ZERO;
                    // item total amount - already applied (if any)
                    BigDecimal alreadyApplied = ZERO;
                    if (UtilValidate.isNotEmpty(paymentApplications)) {
                        // application(s) found, add them all together
                        Iterator<GenericValue> p = paymentApplications.iterator();
                        while (p.hasNext()) {
                            paymentApplication = p.next();
                            alreadyApplied = alreadyApplied.add(paymentApplication
                                    .getBigDecimal("amountApplied").setScale(DECIMALS, ROUNDING));
                        }
                        tobeApplied = itemTotal.subtract(alreadyApplied).setScale(DECIMALS, ROUNDING);
                    } else {
                        // no application connected yet
                        tobeApplied = itemTotal;
                    }
                    if (debug)
                        Debug.logInfo("tobeApplied:(" + tobeApplied + ") = " + "itemTotal(" + itemTotal
                                + ") - alreadyApplied(" + alreadyApplied
                                + ") but not more then (nonapplied) paymentAmount(" + paymentApplyAvailable
                                + ")", module);

                    if (tobeApplied.signum() == 0) {
                        // invoiceItem already fully applied so look at the next one....
                        continue;
                    }

                    if (paymentApplyAvailable.compareTo(tobeApplied) > 0) {
                        paymentApplyAvailable = paymentApplyAvailable.subtract(tobeApplied);
                    } else {
                        tobeApplied = paymentApplyAvailable;
                        paymentApplyAvailable = ZERO;
                    }

                    // create application payment record but check currency
                    // first if supplied
                    if (invoice.get("currencyUomId") != null && currencyUomId != null
                            && !invoice.getString("currencyUomId").equals(currencyUomId)) {
                        errorMessageList.add("Payment currency (" + currencyUomId + ") and invoice currency("
                                + invoice.getString("currencyUomId") + ") not the same\n");
                    } else {
                        paymentApplication.set("paymentApplicationId", null);
                        // make sure we get a new record
                        paymentApplication.set("invoiceId", invoiceId);
                        paymentApplication.set("invoiceItemSeqId",
                                currentInvoiceItem.getString("invoiceItemSeqId"));
                        paymentApplication.set("paymentId", paymentId);
                        paymentApplication.set("toPaymentId", toPaymentId);
                        paymentApplication.set("amountApplied", tobeApplied);
                        paymentApplication.set("billingAccountId", billingAccountId);
                        paymentApplication.set("taxAuthGeoId", taxAuthGeoId);
                        storePaymentApplication(delegator, paymentApplication, locale);
                    }

                }

                if (errorMessageList.size() > 0) {
                    return ServiceUtil.returnError(errorMessageList);
                } else {
                    if (successMessage != null) {
                        return ServiceUtil.returnSuccess(successMessage);
                    } else {
                        return ServiceUtil.returnSuccess();
                    }
                }
            }
        }
    }

    // if no paymentApplicationId supplied create a new record with the data
    // supplied...
    if (paymentApplicationId == null && amountApplied != null) {
        paymentApplication.set("paymentApplicationId", paymentApplicationId);
        paymentApplication.set("invoiceId", invoiceId);
        paymentApplication.set("invoiceItemSeqId", invoiceItemSeqId);
        paymentApplication.set("paymentId", paymentId);
        paymentApplication.set("toPaymentId", toPaymentId);
        paymentApplication.set("amountApplied", amountApplied);
        paymentApplication.set("billingAccountId", billingAccountId);
        paymentApplication.set("taxAuthGeoId", taxAuthGeoId);
        return storePaymentApplication(delegator, paymentApplication, locale);
    }

    // should never come here...
    errorMessageList.add(
            UtilProperties.getMessage(resource, "AccountingPaymentApplicationParameterUnsuitable", locale));
    errorMessageList
            .add(UtilProperties.getMessage(resource, "AccountingPaymentApplicationParameterListUnsuitable",
                    UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId, "paymentId",
                            paymentId, "toPaymentId", toPaymentId, "paymentApplicationId", paymentApplicationId,
                            "amountApplied", amountApplied),
                    locale));
    return ServiceUtil.returnError(errorMessageList);
}

From source file:com.att.pirates.controller.ProjectController.java

private static String getRowDueDatePercentageString(String Percentage, String Duedate, String UpdatedByUUID,
        String uuid, String headerDueDate, boolean left, boolean validateThreshold) {
    String[] datecreatedList = Duedate.split(",");
    String[] percentageList = Percentage.split(",");
    String[] uuidList = UpdatedByUUID.split(",");

    SimpleDateFormat xFormat = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat yFormat = new SimpleDateFormat("MM/dd/yy");

    if (datecreatedList == null || datecreatedList.length == 0) {
        return "NA";
    }//w  ww.  ja  va  2 s  . com

    if (("NA".equalsIgnoreCase(datecreatedList[0])) || ("NA".equalsIgnoreCase(headerDueDate))) {
        return "NA";
    }

    if (percentageList.length != datecreatedList.length) {
        //logger.error("Error, DateCreated count does not equal Percentage count");
        return "";
    }

    try {
        // mchan: added code to evaluate if the latest updated date fits in the threashold
        // get threshold info for user, 1 = noupdate, 2 = duein
        List<Threshold> thresholds = DataService.getEmployeeThresholds(uuid);
        String warningMsg = "";

        if (thresholds != null && !thresholds.isEmpty() && validateThreshold) {
            // since we have a list of dates, we just need the max
            List<Integer> noupdates = new ArrayList<Integer>();
            List<Integer> dueins = new ArrayList<Integer>();
            String percent = percentageList[0];
            BigDecimal d = new BigDecimal(percent.trim().replace("%", "")).divide(BigDecimal.valueOf(100));
            if (d.compareTo(BigDecimal.ONE) == 0) {
                //logger.error(d + ", is exactly one");
            } else if (d.compareTo(BigDecimal.ONE) == 1) {
                //logger.error(d + ", is greater than one");
            } else if (d.compareTo(BigDecimal.ONE) == -1) {
                //logger.error(d + ", is less than one");
            }

            for (Threshold t : thresholds) {
                // process NoUpdate
                if (PiratesConstants.NOUPDATE.equalsIgnoreCase(t.getThresholdType())) {
                    try {
                        noupdates.add(Integer.parseInt(t.getThresholdValue()));
                    } catch (NumberFormatException ex) {
                        //logger.error("Error parsing threshold value, type: NOUPDATE, value: " + t.getThresholdValue());
                    }
                }
                // process DueIn
                if (PiratesConstants.DUEIN.equalsIgnoreCase(t.getThresholdType())) {
                    try {
                        dueins.add(Integer.parseInt(t.getThresholdValue()));
                    } catch (NumberFormatException ex) {
                        //logger.error("Error parsing threshold value, type: DUEIN, value: " + t.getThresholdValue());
                    }
                }
            } // done parsing thresholds                   

            if (!noupdates.isEmpty() && (d.compareTo(BigDecimal.ONE) == -1)
                    && (!"NA".equalsIgnoreCase(datecreatedList[0])) && validateThreshold) {
                // compare dates, last updated and today and then match it with the maxnoupdate and maxduein
                // last updated date
                Date lastUpdated = xFormat.parse(datecreatedList[0]);
                Date today = new Date();
                if (lastUpdated.before(today)) {
                    long diff = today.getTime() - lastUpdated.getTime();
                    int diffindays = (int) (diff / (24 * 60 * 60 * 1000));

                    Collections.sort(noupdates);
                    Integer[] foo = noupdates.toArray(new Integer[noupdates.size()]);
                    // now in descending order
                    ArrayUtils.reverse(foo);
                    for (Integer i : foo) {
                        if (diffindays >= i) {
                            warningMsg = "Status is static for more than " + String.valueOf(i) + " days! <br/>";
                            break;
                        }
                    }
                } else {
                    warningMsg = "Today cannot be before LastUpdatedDate ??!";
                }
            }

            // check artifact due in x number if days, but ignore NA
            if ((!dueins.isEmpty()) && (d.compareTo(BigDecimal.ONE) == -1)
                    && (!"NA".equalsIgnoreCase(headerDueDate))) {
                Collections.sort(dueins);
                Date dueDate = xFormat.parse(headerDueDate);
                Date today = new Date();

                if (today.before(dueDate)) {
                    // logger.error("dueDate.getTime() is: " + dueDate.getTime());
                    // logger.error("today.getTime() is: " + today.getTime());

                    long diff = dueDate.getTime() - today.getTime();
                    int diffindays = (int) (diff / (24 * 60 * 60 * 1000));
                    // logger.error("dueDate.getTime() - today.getTime() is: " + diffindays);

                    Collections.sort(dueins);
                    Integer[] foo = dueins.toArray(new Integer[dueins.size()]);
                    // now in descending order
                    ArrayUtils.reverse(foo);
                    for (Integer i : foo) {
                        if (diffindays <= i) {
                            warningMsg = warningMsg + "Artifact is due in "
                                    + (diffindays == 0 ? "less than a day"
                                            : String.valueOf(diffindays) + " days");
                            break;
                        }
                    }
                } else {
                    // logger.error("header duedate is: " + dueDate);
                    // logger.error("today is: " + today);    
                    // logger.error("Today is NOT before due date ??");
                    warningMsg = warningMsg + "Project overdue";
                }
            }
        } // end processing thresholds

        int i = 0;
        // display in dropdown from greatest to least, so we need to revert the array
        StringBuilder selectHtml = new StringBuilder();

        if (!warningMsg.isEmpty()) {
            selectHtml.append(
                    "<div class='dropdown'> <button style='background-color: #FF8080' class='btn btn-default dropdown-toggle' type='button' id='dropdownMenu1' data-toggle='dropdown' aria-expanded='true'>");
        } else {
            selectHtml.append(
                    "<div class='dropdown'> <button class='btn btn-default dropdown-toggle' type='button' id='dropdownMenu1' data-toggle='dropdown' aria-expanded='true'>");
        }
        selectHtml.append(yFormat.format(xFormat.parse(datecreatedList[0]))).append("&nbsp;&nbsp;")
                .append(percentageList[0]);
        selectHtml.append("<span class='caret'></span></button>");
        selectHtml.append("<ul class='dropdown-menu' role='menu' aria-labelledby='dropdownMenu1'>");

        for (String s : datecreatedList) {
            String tmplblBRduedate = yFormat.format(xFormat.parse(s));
            // logger.error("DueDate is: " + tmplblBRduedate);
            String percentStr = percentageList[i];
            String byuuidstr = uuidList[i];
            String newUUID = getATTEmployeeObjectByUUID(byuuidstr).getFullName();
            if (i == 0 && !warningMsg.isEmpty()) {
                if (!left) {
                    // tooltip on the right side
                    selectHtml.append("<li role='presentation'>")
                            .append("<a role='menuitem' tabindex='-1' href='#'>").append(tmplblBRduedate)
                            .append("&nbsp;&nbsp;" + percentStr + "&nbsp;")
                            .append("<span class='glyphicon glyphicon-question-sign question' id='mytimestamp' data='")
                            .append(warningMsg).append("'></span>").append("</a>").append("</li>");
                } else {
                    // tooltip on left
                    selectHtml.append(
                            "<li role='presentation'><a role='menuitem' tabindex='-1' href='#'><span class='glyphicon glyphicon-question-sign question' id='mytimestamp' data='")
                            .append(warningMsg).append("'></span> &nbsp;").append(tmplblBRduedate)
                            .append("&nbsp;&nbsp;" + percentStr + "</a> </li>");
                }
            } else {
                if (!left) {
                    // tooltip on the right side
                    selectHtml.append("<li role='presentation'>")
                            .append("<a role='menuitem' tabindex='-1' href='#'>").append(tmplblBRduedate)
                            .append("&nbsp;&nbsp;" + percentStr + "&nbsp;")
                            .append("<span class='glyphicon glyphicon-question-sign question' id='mytimestamp' data='")
                            .append("Last updated by: " + newUUID).append("'></span>").append("</a>")
                            .append("</li>");
                } else {
                    selectHtml.append(
                            "<li role='presentation'><a role='menuitem' tabindex='-1' href='#'><span class='glyphicon glyphicon-question-sign question' id='mytimestamp' data='")
                            .append("Last updated by: " + newUUID).append("'></span> &nbsp;")
                            .append(tmplblBRduedate).append("&nbsp;&nbsp;" + percentStr + "</a> </li>");
                }
            }
            i++;
        }

        selectHtml.append("</ul>");
        selectHtml.append("</div>");
        return selectHtml.toString();
    } catch (Exception ex) {
        logger.error(msgHeader + "Error occurred getRowDueDatePercentageString... " + ex.getMessage());
    }
    return null;
}

From source file:com.tasktop.c2c.server.tasks.tests.service.TaskServiceTest.java

License:asdf

@Test
public void createTask_withWorkLog() throws Exception {
    com.tasktop.c2c.server.tasks.domain.Task mockTask = getMockTask();
    WorkLog worklog = new WorkLog();
    worklog.setProfile(ProfileConverter.copy(currentUser));
    Date now = new Date();
    worklog.setDateWorked(now);//w w w.j  av  a 2  s. com
    worklog.setHoursWorked(new BigDecimal(1.0));
    mockTask.getWorkLogs().add(worklog);
    com.tasktop.c2c.server.tasks.domain.Task createdTask = taskService.createTask(mockTask);

    assertEquals(1, createdTask.getWorkLogs().size());
    assertEquals(BigDecimal.ONE, createdTask.getWorkLogs().get(0).getHoursWorked());

    // the date that is stored is set by the client, not the server
    assertEquals(0, now.compareTo(createdTask.getWorkLogs().get(0).getDateWorked()));
}

From source file:org.ofbiz.order.order.OrderServices.java

public static Map<String, Object> addItemToApprovedOrder(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    String shipGroupSeqId = (String) context.get("shipGroupSeqId");
    String orderId = (String) context.get("orderId");
    String productId = (String) context.get("productId");
    String prodCatalogId = (String) context.get("prodCatalogId");
    BigDecimal basePrice = (BigDecimal) context.get("basePrice");
    BigDecimal quantity = (BigDecimal) context.get("quantity");
    BigDecimal amount = (BigDecimal) context.get("amount");
    Timestamp itemDesiredDeliveryDate = (Timestamp) context.get("itemDesiredDeliveryDate");
    String overridePrice = (String) context.get("overridePrice");
    String reasonEnumId = (String) context.get("reasonEnumId");
    String changeComments = (String) context.get("changeComments");
    Boolean calcTax = (Boolean) context.get("calcTax");
    if (calcTax == null) {
        calcTax = Boolean.TRUE;//from  w w w .  j  a v  a 2s  .  c  o  m
    }

    if (amount == null) {
        amount = BigDecimal.ZERO;
    }

    int shipGroupIdx = -1;
    try {
        shipGroupIdx = Integer.parseInt(shipGroupSeqId);
        shipGroupIdx--;
    } catch (NumberFormatException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    if (shipGroupIdx < 0) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderShipGroupSeqIdInvalid",
                UtilMisc.toMap("shipGroupSeqId", shipGroupSeqId), locale));
    }

    // obtain a shopping cart object for updating
    ShoppingCart cart = null;
    try {
        cart = loadCartForUpdate(dispatcher, delegator, userLogin, orderId);
    } catch (GeneralException e) {
        return ServiceUtil.returnError(e.getMessage());
    }
    if (cart == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderShoppingCartEmpty", locale));
    }

    // add in the new product
    try {
        if ("PURCHASE_ORDER".equals(cart.getOrderType())) {
            GenericValue supplierProduct = cart.getSupplierProduct(productId, quantity, dispatcher);
            ShoppingCartItem item = null;
            if (supplierProduct != null) {
                item = ShoppingCartItem.makePurchaseOrderItem(null, productId, null, quantity, null, null,
                        prodCatalogId, null, null, null, dispatcher, cart, supplierProduct,
                        itemDesiredDeliveryDate, itemDesiredDeliveryDate, null);
                cart.addItem(0, item);
            } else {
                throw new CartItemModifyException("No supplier information found for product [" + productId
                        + "] and quantity quantity [" + quantity + "], cannot add to cart.");
            }

            if (basePrice != null) {
                item.setBasePrice(basePrice);
                item.setIsModifiedPrice(true);
            }

            cart.setItemShipGroupQty(item, item.getQuantity(), shipGroupIdx);
        } else {
            ShoppingCartItem item = ShoppingCartItem.makeItem(null, productId, null, quantity, null, null, null,
                    null, null, null, null, null, prodCatalogId, null, null, null, dispatcher, cart, null, null,
                    null, Boolean.FALSE, Boolean.FALSE);
            if (basePrice != null && overridePrice != null) {
                item.setBasePrice(basePrice);
                // special hack to make sure we re-calc the promos after a price change
                item.setQuantity(quantity.add(BigDecimal.ONE), dispatcher, cart, false);
                item.setQuantity(quantity, dispatcher, cart, false);
                item.setBasePrice(basePrice);
                item.setIsModifiedPrice(true);
            }

            // set the item in the selected ship group
            item.setShipBeforeDate(itemDesiredDeliveryDate);
            cart.clearItemShipInfo(item);
            cart.setItemShipGroupQty(item, item.getQuantity(), shipGroupIdx);
        }
    } catch (CartItemModifyException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    } catch (ItemNotFoundException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }

    Map<String, Object> changeMap = UtilMisc.<String, Object>toMap("itemReasonMap",
            UtilMisc.<String, Object>toMap("reasonEnumId", reasonEnumId), "itemCommentMap",
            UtilMisc.<String, Object>toMap("changeComments", changeComments));
    // save all the updated information
    try {
        saveUpdatedCartToOrder(dispatcher, delegator, cart, locale, userLogin, orderId, changeMap, calcTax,
                false);
    } catch (GeneralException e) {
        return ServiceUtil.returnError(e.getMessage());
    }

    // log an order note
    try {
        String addedItemToOrder = UtilProperties.getMessage(resource, "OrderAddedItemToOrder", locale);
        dispatcher.runSync("createOrderNote",
                UtilMisc.<String, Object>toMap("orderId", orderId, "note",
                        addedItemToOrder + productId + " (" + quantity + ")", "internalNote", "Y", "userLogin",
                        userLogin));
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("shoppingCart", cart);
    result.put("orderId", orderId);
    return result;
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String sendSiRespBase() {
    String pagina = null;//from  ww w.j a v a2 s .  com
    try {

        if (StringUtils.isBlank(this.getSelectedBaseLegal().getVmsjusuariocreacion())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                    "Campo requerido. Ingrese el mensaje a enviar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            pagina = null;
        } else {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User usuario = loginMB.getUser();
            if (this.getChkDestacado()) {
                ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
                HashMap filter = new HashMap();
                filter.put("ntipoconocimientoid", Constante.BASELEGAL);
                BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
                if (cant.intValue() >= 10) {
                    this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                    RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                    return "";
                }
            }
            if (!CollectionUtils.isEmpty(this.getListaTarget())) {
                for (BaseLegal v : this.getListaTarget()) {
                    if (v.getNestadoid().equals(BigDecimal.ZERO)) {
                        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                                "Debe seleccionar el estado de todos los vnculos agregados.");
                        FacesContext.getCurrentInstance().addMessage(null, message);
                        return "";
                    }
                }
            }
            if (this.getSelectedCategoria() != null) {
                this.getSelectedBaseLegal().setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
            }
            BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
            this.getSelectedBaseLegal()
                    .setVnombre(StringUtils.capitalize(this.getSelectedBaseLegal().getVnombre()));
            this.getSelectedBaseLegal().setVnumero(
                    this.getTipoNorma().concat(" - ").concat(StringUtils.upperCase(this.getNumeroNorma())));
            this.getSelectedBaseLegal().setNrangoid(this.getSelectedBaseLegal().getNrangoid());
            this.getSelectedBaseLegal()
                    .setNgobnacional(this.getChkGobNacional() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal()
                    .setNgobregional(this.getChkGobRegional() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal().setNgoblocal(this.getChkGobLocal() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal()
                    .setNmancomunidades(this.getChkMancomunidades() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal()
                    .setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedBaseLegal().setVsumilla(this.getSelectedBaseLegal().getVsumilla().trim());
            this.getSelectedBaseLegal()
                    .setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
            this.getSelectedBaseLegal().setVtema(this.getSelectedBaseLegal().getVtema());
            this.getSelectedBaseLegal().setVusuariomodificacion(usuario.getVlogin());
            this.getSelectedBaseLegal().setDfechamodificacion(new Date());
            this.getSelectedBaseLegal()
                    .setVmsjusuariocreacion(this.getSelectedBaseLegal().getVmsjusuariocreacion().toUpperCase());
            service.saveOrUpdate(this.getSelectedBaseLegal());

            BaseLegalHistorialService serviceHistorial = (BaseLegalHistorialService) ServiceFinder
                    .findBean("BaseLegalHistorialService");
            BaselegalHist hist = serviceHistorial
                    .getLastHistorialByBaselegal(this.getSelectedBaseLegal().getNbaselegalid());

            BaselegalHist baseHist = new BaselegalHist();
            baseHist.setNhistorialid(serviceHistorial.getNextPK());
            baseHist.setNbaselegalid(this.getSelectedBaseLegal().getNbaselegalid());
            baseHist.setNcategoriaid(this.getSelectedBaseLegal().getNcategoriaid());
            baseHist.setVnombre(this.getSelectedBaseLegal().getVnombre());
            baseHist.setVnumero(this.getSelectedBaseLegal().getVnumero());
            baseHist.setNrangoid(this.getSelectedBaseLegal().getNrangoid());
            baseHist.setNgobnacional(this.getSelectedBaseLegal().getNgobnacional());
            baseHist.setNgobregional(this.getSelectedBaseLegal().getNgobregional());
            baseHist.setNgoblocal(this.getSelectedBaseLegal().getNgoblocal());
            baseHist.setNmancomunidades(this.getSelectedBaseLegal().getNmancomunidades());
            baseHist.setNdestacado(this.getSelectedBaseLegal().getNdestacado());
            baseHist.setVsumilla(this.getSelectedBaseLegal().getVsumilla());
            baseHist.setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
            baseHist.setVtema(this.getSelectedBaseLegal().getVtema());
            baseHist.setNactivo(this.getSelectedBaseLegal().getNactivo());
            baseHist.setNestadoid(this.getSelectedBaseLegal().getNestadoid());
            baseHist.setNversion(BigDecimal.valueOf(hist.getNversion().intValue() + 1));
            baseHist.setVusuariocreacion(usuario.getVlogin());
            baseHist.setDfechacreacion(new Date());
            baseHist.setVusuariomodificacion(this.getSelectedBaseLegal().getVusuariomodificacion());
            baseHist.setDfechamodificacion(this.getSelectedBaseLegal().getDfechamodificacion());
            serviceHistorial.saveOrUpdate(baseHist);

            Tbaselegal tbaselegal = new Tbaselegal();
            BeanUtils.copyProperties(tbaselegal, this.getSelectedBaseLegal());

            String ruta0 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                    + BigDecimal.ZERO.toString() + "/";
            String ruta1 = path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "/"
                    + baseHist.getNversion().toString() + "/";

            ArchivoService aservice = (ArchivoService) ServiceFinder.findBean("ArchivoService");
            Archivo archivo = aservice.getArchivoByBaseLegal(this.getSelectedBaseLegal());
            if (this.getUploadFile() != null) {
                archivo.setVnombre(this.getUploadFile().getFileName());
                archivo.setVruta(ruta0 + archivo.getVnombre());
                archivo.setVusuariomodificacion(usuario.getVlogin());
                archivo.setDfechamodificacion(new Date());
                aservice.saveOrUpdate(archivo);
                saveFile(ruta0);
            }

            ArchivoHistorialService aserviceHist = (ArchivoHistorialService) ServiceFinder
                    .findBean("ArchivoHistorialService");
            ArchivoHist aHist = aserviceHist.getLastArchivoHistByBaseLegalHist(baseHist);

            ArchivoHist archivoHist = new ArchivoHist();
            archivoHist.setNarchivohistid(aserviceHist.getNextPK());
            archivoHist.setNhistorialid(baseHist.getNhistorialid());
            archivoHist.setNbaselegalid(baseHist.getNbaselegalid());
            archivoHist.setVnombre(archivo.getVnombre());
            archivoHist.setVruta(ruta1 + archivo.getVnombre());
            archivoHist.setVusuariocreacion(usuario.getVlogin());
            archivoHist.setDfechacreacion(new Date());
            aserviceHist.saveOrUpdate(archivoHist);
            saveFile(ruta1);

            VinculoBaseLegalService vservice = (VinculoBaseLegalService) ServiceFinder
                    .findBean("VinculoBaseLegalService");
            vservice.deleteByBaseLegal(this.getSelectedBaseLegal());
            for (BaseLegal v : this.getListaTarget()) {
                TvinculoBaselegalId id = new TvinculoBaselegalId();
                id.setNbaselegalid(tbaselegal.getNbaselegalid());
                id.setNvinculoid(vservice.getNextPK());
                VinculoBaselegal vinculo = new VinculoBaselegal();
                vinculo.setId(id);
                vinculo.setTbaselegal(tbaselegal);
                vinculo.setNbaselegalvinculadaid(v.getNbaselegalid());
                vinculo.setNtipovinculo(v.getNestadoid());
                vinculo.setDfechacreacion(new Date());
                vinculo.setVusuariocreacion(usuario.getVlogin());
                vservice.saveOrUpdate(vinculo);

                BaseLegal blvinculada = service.getBaselegalById(v.getNbaselegalid());
                blvinculada.setNestadoid(v.getNestadoid());
                blvinculada.setDfechamodificacion(new Date());
                blvinculada.setVusuariomodificacion(usuario.getVlogin());
                service.saveOrUpdate(blvinculada);

                if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_MODIFICADA)
                        || v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_CONCORDADO)) {

                    ConocimientoService cservice = (ConocimientoService) ServiceFinder
                            .findBean("ConocimientoService");
                    List<Consulta> listaConocimientos = cservice
                            .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                    for (Consulta c : listaConocimientos) {
                        Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                        conocimiento.setDfechamodificacion(new Date());
                        conocimiento.setVusuariomodificacion(usuario.getVlogin());
                        String descHtml = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                                "html.txt");
                        String descPlain = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                                "plain.txt");
                        cservice.saveOrUpdate(conocimiento);

                        HistorialService historialService = (HistorialService) ServiceFinder
                                .findBean("HistorialService");
                        Historial lastHistorial = historialService
                                .getLastHistorialByConocimiento(conocimiento.getNconocimientoid());
                        int lastversion;
                        if (lastHistorial != null) {
                            lastversion = lastHistorial.getNnumversion().intValue();
                        } else {
                            lastversion = 0;
                        }
                        String newpath = "";
                        if (conocimiento.getNtipoconocimientoid().equals(Constante.BASELEGAL)) {
                            newpath = "bl/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.BUENAPRACTICA)) {
                            newpath = "bp/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.CONTENIDO)) {
                            newpath = "ct/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.OPORTUNIDADMEJORA)) {
                            newpath = "om/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.PREGUNTAS)) {
                            newpath = "pr/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.WIKI)) {
                            newpath = "wk/";
                        }

                        String url = newpath.concat(conocimiento.getNconocimientoid().toString()).concat("/")
                                .concat(Integer.toString(lastversion + 1)).concat("/");

                        ThistorialId thistorialId = new ThistorialId();
                        thistorialId.setNconocimientoid(conocimiento.getNconocimientoid());
                        thistorialId.setNhistorialid(historialService.getNextPK());
                        Historial historial = new Historial();
                        historial.setId(thistorialId);
                        historial.setNtipoconocimientoid(conocimiento.getNtipoconocimientoid());
                        historial.setNcategoriaid(conocimiento.getNcategoriaid());
                        historial.setVtitulo(conocimiento.getVtitulo());
                        historial.setNactivo(BigDecimal.ONE);
                        historial.setNsituacionid(conocimiento.getNsituacionid());
                        historial.setVruta(url);
                        historial.setNnumversion(BigDecimal.valueOf(lastversion + 1));
                        historial.setDfechacreacion(new Date());
                        historial.setVusuariocreacion(usuario.getVlogin());
                        historialService.saveOrUpdate(historial);

                        GcmFileUtils.writeStringToFileServer(url, "html.txt", descHtml);
                        GcmFileUtils.writeStringToFileServer(url, "plain.txt", descPlain);

                        SeccionService seccionService = (SeccionService) ServiceFinder
                                .findBean("SeccionService");
                        SeccionHistService seccionHistService = (SeccionHistService) ServiceFinder
                                .findBean("SeccionHistService");
                        List<Seccion> listaSecc = seccionService
                                .getSeccionesByConocimiento(conocimiento.getNconocimientoid());
                        if (!CollectionUtils.isEmpty(listaSecc)) {
                            String url0 = conocimiento.getVruta().concat("s");
                            String url1 = url.concat("s");
                            for (Seccion seccion : listaSecc) {
                                seccion.setDetalleHtml(
                                        GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                                ruta0 = url0.concat(seccion.getNorden().toString()).concat("/");
                                seccion.setVruta(ruta0);
                                seccion.setDfechamodificacion(new Date());
                                seccion.setVusuariomodificacion(usuario.getVlogin());
                                seccionService.saveOrUpdate(seccion);

                                seccion.setDetallePlain(Jsoup.parse(seccion.getDetalleHtml()).text());

                                ruta1 = url1.concat(seccion.getNorden().toString()).concat("/");
                                TseccionHistId tseccionHistId = new TseccionHistId();
                                tseccionHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                                tseccionHistId.setNhistorialid(thistorialId.getNhistorialid());
                                tseccionHistId.setNseccionhid(seccionHistService.getNextPK());
                                SeccionHist seccionHist = new SeccionHist();
                                seccionHist.setId(tseccionHistId);
                                seccionHist.setNorden(seccion.getNorden());
                                seccionHist.setVruta(ruta1);
                                seccionHist.setVtitulo(seccion.getVtitulo());
                                seccionHist.setVusuariocreacion(usuario.getVlogin());
                                seccionHist.setDfechacreacion(new Date());
                                seccionHistService.saveOrUpdate(seccionHist);

                                GcmFileUtils.writeStringToFileServer(ruta1, "html.txt",
                                        seccion.getDetalleHtml());
                                GcmFileUtils.writeStringToFileServer(ruta1, "plain.txt",
                                        seccion.getDetallePlain());
                            }
                        }

                        VinculoService vinculoService = (VinculoService) ServiceFinder
                                .findBean("VinculoService");
                        Vinculo vinculoC = new Vinculo();
                        vinculoC.setNvinculoid(vinculoService.getNextPK());
                        vinculoC.setNconocimientoid(conocimiento.getNconocimientoid());
                        vinculoC.setNconocimientovinc(tbaselegal.getNbaselegalid());
                        vinculoC.setNtipoconocimientovinc(Constante.BASELEGAL);
                        vinculoC.setDfechacreacion(new Date());
                        vinculoC.setVusuariocreacion(usuario.getVlogin());
                        vinculoService.saveOrUpdate(vinculoC);

                        List<Vinculo> vinculos = vinculoService
                                .getVinculosByConocimiento(conocimiento.getNtipoconocimientoid());
                        VinculoHistService vinculoHistService = (VinculoHistService) ServiceFinder
                                .findBean("VinculoHistService");
                        for (Vinculo vinc : vinculos) {
                            TvinculoHistId vinculoHistId = new TvinculoHistId();
                            vinculoHistId.setNvinculohid(vinculoHistService.getNextPK());
                            vinculoHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                            vinculoHistId.setNhistorialid(thistorialId.getNhistorialid());
                            VinculoHist vinculoHist = new VinculoHist();
                            vinculoHist.setId(vinculoHistId);
                            vinculoHist.setNconocimientovinc(vinc.getNconocimientovinc());
                            vinculoHist.setDfechacreacion(new Date());
                            vinculoHist.setVusuariocreacion(usuario.getVlogin());
                            vinculoHistService.saveOrUpdate(vinculoHist);
                        }
                    }
                } else if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_DEROGADA)) {
                    ConocimientoService cservice = (ConocimientoService) ServiceFinder
                            .findBean("ConocimientoService");
                    List<Consulta> listaConocimientos = cservice
                            .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                    for (Consulta c : listaConocimientos) {
                        Conocimiento conocimiento = cservice.getConocimientoById(c.getId());
                        conocimiento.setNflgvinculo(BigDecimal.ONE);
                        conocimiento.setDfechamodificacion(new Date());
                        conocimiento.setVusuariomodificacion(usuario.getVlogin());
                    }
                }

                VinculoBaselegalHistorialService vserviceHist = (VinculoBaselegalHistorialService) ServiceFinder
                        .findBean("VinculoBaselegalHistorialService");
                VinculoBaselegalHist vinculoHist = new VinculoBaselegalHist();
                vinculoHist.setNvinculohistid(vserviceHist.getNextPK());
                vinculoHist.setNhistorialid(baseHist.getNhistorialid());
                vinculoHist.setNbaselegalid(baseHist.getNbaselegalid());
                vinculoHist.setNbaselegalvinculadaid(v.getNbaselegalid());
                vinculoHist.setNtipovinculo(v.getNestadoid());
                vinculoHist.setDfechacreacion(new Date());
                vinculoHist.setVusuariocreacion(usuario.getVlogin());
                vserviceHist.saveOrUpdate(vinculoHist);
            }

            AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
            this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            this.getSelectedAsignacion().setDfechaatencion(new Date());
            this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("10")));
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            Asignacion asignacion = new Asignacion();
            asignacion.setNasignacionid(serviceasig.getNextPK());
            asignacion.setNtipoconocimientoid(Constante.BASELEGAL);
            asignacion.setNconocimientoid(this.getSelectedBaseLegal().getNbaselegalid());
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("1")));
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            asignacion.setNusuarioid(categoriaService
                    .getCategoriaById(this.getSelectedBaseLegal().getNcategoriaid()).getNmoderador());
            asignacion.setDfechaasignacion(new Date());
            asignacion.setDfechacreacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            loginMB.refreshNotifications();

            pagina = "/index.xhtml";
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return pagina;
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public void saveContenidoEdit(ActionEvent event) {
    String pagina = null;/*from   w ww.  j  ava2s  .c  o  m*/
    try {
        LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
        User user_savecontenido = loginMB.getUser();
        //this.setContenidoHtml(JSFUtils.getRequestParameter("descHtml"));
        if (this.getChkDestacado()) {
            ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
            HashMap filter = new HashMap();
            filter.put("ntipoconocimientoid", Constante.CONTENIDO);
            BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
            if (cant.intValue() >= 10) {
                this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                return;
            }
        }
        ContenidoService service = (ContenidoService) ServiceFinder.findBean("ContenidoService");
        this.setContenidoPlain(Jsoup.parse(this.getContenidoHtml()).text());
        this.getSelectedContenido().setVtitulo(this.getSelectedContenido().getVtitulo().trim());
        this.getSelectedContenido().setVdescripcion(this.getSelectedContenido().getVdescripcion().trim());
        if (this.getContenidoPlain().length() < 400) {
            this.getSelectedContenido().setVcontenido(StringUtils.capitalize(this.getContenidoPlain()));
        } else {
            this.getSelectedContenido()
                    .setVcontenido(StringUtils.capitalize(this.getContenidoPlain().substring(0, 399)));
        }

        if (this.getSelectedCategoria() == null) {
            this.getSelectedContenido().setNcategoriaid(this.getSelectedContenido().getNcategoriaid());
            cat_nueva = this.getSelectedContenido().getNcategoriaid();
        } else {
            this.getSelectedContenido().setNcategoriaid(this.getSelectedContenido().getNcategoriaid());
            cat_nueva = this.getSelectedContenido().getNcategoriaid();
        }

        this.getSelectedContenido().setDfechamodificacion(new Date());
        this.getSelectedContenido().setVusuariomodificacion(user_savecontenido.getVlogin());
        service.saveOrUpdate(this.getSelectedContenido());

        GcmFileUtils.writeStringToFileServer(this.getSelectedContenido().getVruta(), "html.txt",
                this.getContenidoHtml());
        GcmFileUtils.writeStringToFileServer(this.getSelectedContenido().getVruta(), "plain.txt",
                this.getContenidoPlain());

        HistorialService historialService = (HistorialService) ServiceFinder.findBean("HistorialService");
        Historial lastHistorial = historialService
                .getLastHistorialByConocimiento(this.getSelectedContenido().getNconocimientoid());
        int lastversion;
        if (lastHistorial != null) {
            lastversion = lastHistorial.getNnumversion().intValue();
        } else {
            lastversion = 0;
        }

        String url = this.path.concat(this.getSelectedContenido().getNconocimientoid().toString()).concat("/")
                .concat(Integer.toString(lastversion + 1)).concat("/");

        ThistorialId thistorialId = new ThistorialId();
        thistorialId.setNconocimientoid(this.getSelectedContenido().getNconocimientoid());
        thistorialId.setNhistorialid(historialService.getNextPK());
        Historial historial = new Historial();
        historial.setId(thistorialId);
        historial.setNtipoconocimientoid(Constante.CONTENIDO);
        historial.setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
        historial.setVdescripcion(this.getSelectedContenido().getVdescripcion().trim());
        historial.setVtitulo(this.getSelectedContenido().getVtitulo());
        if (this.getContenidoPlain().length() < 400) {
            historial.setVcontenido(StringUtils.capitalize(this.getContenidoPlain()));
        } else {
            historial.setVcontenido(StringUtils.capitalize(this.getContenidoPlain().substring(0, 399)));
        }
        historial.setNactivo(BigDecimal.ONE);
        historial.setNsituacionid(this.getSelectedContenido().getNsituacionid());
        historial.setVruta(url);
        historial.setNnumversion(BigDecimal.valueOf(lastversion + 1));
        historial.setDfechacreacion(new Date());
        historial.setVmsjsolicita(this.getSelectedContenido().getVmsjsolicita());
        historial.setVmsjrespuesta(this.getSelectedContenido().getVmsjrespuesta());
        historial.setVusuariocreacion(user_savecontenido.getVlogin());
        historialService.saveOrUpdate(historial);

        GcmFileUtils.writeStringToFileServer(url, "html.txt", this.getContenidoHtml());
        GcmFileUtils.writeStringToFileServer(url, "plain.txt", this.getContenidoPlain());

        this.setListaTargetVinculos(new ArrayList<Consulta>());

        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBL())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBL());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBP())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBP());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosCT())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosCT());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosOM())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosOM());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosPR())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosPR());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosWK())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosWK());
        }

        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(this.getListaTargetVinculos())) {
            VinculoService vinculoService = (VinculoService) ServiceFinder.findBean("VinculoService");
            VinculoHistService vinculoHistService = (VinculoHistService) ServiceFinder
                    .findBean("VinculoHistService");
            service.delete(this.getSelectedContenido().getNconocimientoid());
            for (Consulta consulta : this.getListaTargetVinculos()) {
                Vinculo vinculo = new Vinculo();
                vinculo.setNvinculoid(vinculoService.getNextPK());
                vinculo.setNconocimientoid(this.getSelectedContenido().getNconocimientoid());
                vinculo.setNconocimientovinc(consulta.getIdconocimiento());
                vinculo.setNtipoconocimientovinc(consulta.getIdTipoConocimiento());
                vinculo.setDfechacreacion(new Date());
                vinculo.setVusuariocreacion(user_savecontenido.getVlogin());
                vinculoService.saveOrUpdate(vinculo);

                TvinculoHistId vinculoHistId = new TvinculoHistId();
                vinculoHistId.setNvinculohid(vinculoHistService.getNextPK());
                vinculoHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                vinculoHistId.setNhistorialid(thistorialId.getNhistorialid());
                VinculoHist vinculoHist = new VinculoHist();
                vinculoHist.setId(vinculoHistId);
                vinculoHist.setNconocimientovinc(vinculo.getNconocimientovinc());
                vinculoHist.setNtipoconocimientovinc(vinculo.getNtipoconocimientovinc());
                vinculoHist.setDfechacreacion(new Date());
                vinculoHist.setVusuariocreacion(user_savecontenido.getVlogin());
                vinculoHistService.saveOrUpdate(vinculoHist);
            }
        }

        ArchivoConocimientoService aservice = (ArchivoConocimientoService) ServiceFinder
                .findBean("ArchivoConocimientoService");
        service.deleteArchivos(this.getSelectedContenido().getNconocimientoid());
        for (ArchivoConocimiento v : this.getListaArchivos()) {

            ArchivoConocimiento archivoconocimiento = new ArchivoConocimiento();
            archivoconocimiento.setNarchivoid(aservice.getNextPK());
            archivoconocimiento.setNtipoconocimientoid(Constante.CONTENIDO);
            archivoconocimiento.setNconocimientoid(this.getSelectedContenido().getNconocimientoid());
            archivoconocimiento.setVnombre(v.getVnombre());
            archivoconocimiento.setNversion(historial.getNnumversion());
            archivoconocimiento.setNtipoarchivo(v.getNtipoarchivo());
            archivoconocimiento.setVcontenttype(v.getVcontenttype());
            archivoconocimiento.setVruta(path + this.getSelectedContenido().getNconocimientoid().toString()
                    + "/" + archivoconocimiento.getNversion().toString() + "/"
                    + archivoconocimiento.getVnombre());
            archivoconocimiento.setVusuariocreacion(user_savecontenido.getVlogin());
            archivoconocimiento.setDfechacreacion(new Date());
            aservice.saveOrUpdate(archivoconocimiento);
            saveFileCT(archivoconocimiento);

        }

        if (cat_antigua != cat_nueva) {
            AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
            this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            this.getSelectedAsignacion().setDfechaatencion(new Date());
            this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("12")));
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            Asignacion asignacion = new Asignacion();
            asignacion.setNasignacionid(serviceasig.getNextPK());
            asignacion.setNtipoconocimientoid(Constante.CONTENIDO);
            asignacion.setNconocimientoid(this.getSelectedContenido().getNconocimientoid());
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("1")));
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            asignacion.setNusuarioid(categoriaService
                    .getCategoriaById(this.getSelectedContenido().getNcategoriaid()).getNmoderador());
            asignacion.setDfechaasignacion(new Date());
            asignacion.setDfechacreacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            pagina = "/gescon/index.xhtml";
        } else {
            pagina = "";
        }
        loginMB.refreshNotifications();
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO.",
                "Actualizacin exitosa!.");
        FacesContext.getCurrentInstance().addMessage(null, message);
        FacesContext.getCurrentInstance().getExternalContext().redirect(pagina);
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}