Skip to content

Instantly share code, notes, and snippets.

@danypr92
Created September 9, 2019 10:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danypr92/5d7e79cbb6f2494eb11cf773dbeb2879 to your computer and use it in GitHub Desktop.
Save danypr92/5d7e79cbb6f2494eb11cf773dbeb2879 to your computer and use it in GitHub Desktop.
XML invoicing script...
package org.meveo.service.script;\n\nimport java.io.File;\nimport java.lang.Double;\nimport java.math.BigDecimal;\nimport java.math.RoundingMode;\nimport java.util.ArrayList;\nimport java.util.Date;\nimport java.util.List;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport java.util.concurrent.TimeUnit;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\n\nimport org.meveo.admin.exception.BusinessException;\nimport org.meveo.commons.utils.ParamBeanFactory;\nimport org.meveo.commons.utils.ParamBean;\nimport org.meveo.commons.utils.PersistenceUtils;\nimport org.meveo.model.crm.Provider;\nimport org.meveo.model.admin.Seller;\nimport org.meveo.model.ICustomFieldEntity;\nimport org.meveo.model.admin.User;\nimport org.meveo.model.billing.BankCoordinates;\nimport org.meveo.model.billing.Invoice;\nimport org.meveo.model.billing.RatedTransaction;\nimport org.meveo.model.billing.ServiceInstance;\nimport org.meveo.model.billing.Subscription;\nimport org.meveo.model.billing.WalletOperation;\nimport org.meveo.model.payments.CustomerAccount;\nimport org.meveo.model.payments.PaymentMethod;\nimport org.meveo.model.payments.PaymentMethodEnum;\nimport org.meveo.model.payments.DDPaymentMethod;\nimport org.meveo.model.shared.DateUtils;\nimport org.meveo.service.billing.impl.XMLInvoiceCreator;\nimport org.meveo.service.crm.impl.CustomFieldInstanceService;\nimport org.meveo.service.crm.impl.ProviderService;\nimport org.meveo.service.script.Script;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Element;\nimport org.w3c.dom.Node;\nimport org.w3c.dom.NodeList;\nimport org.w3c.dom.Text;\n\n/**\n *\n * @author anasseh\n * @author Coopdevs\n *\n * Generate custom Xml Invoice needed to fill the Som Connexio invoice\n *\n * Execute Context Variable :\n * <li>CONTEXT_ENTITY : the invoice\n * <li>isVirtual : invoicing mode\n * <li>XMLInvoiceCreator : XMLInvoiceCreator std service\n *\n * Object: [SCN]\n * + Add IBAN from CustomerAccount\n * + Add MSIDSN to every consumption lines\n * + Add Service Description to every consumption lines\n * + Add Subscriptions List to invoice XML\n *\n */\npublic class InvoiceXmlScript extends org.meveo.service.script.Script {\n\n private static final Logger log = LoggerFactory.getLogger(InvoiceXmlScript.class);\n\n private CustomFieldInstanceService cfiService = (CustomFieldInstanceService) getServiceInterface(\"CustomFieldInstanceService\");\n private Provider provider = ((ProviderService)getServiceInterface(\"ProviderService\")).getProvider();\n\n private ParamBean paramBean = ParamBean.getInstance();\n private static String DEFAULT_DATE_PATTERN = \"dd/MM/yyyy\";\n private static String DEFAULT_TIME_PATTERN = \"dd/MM/yyyy\";\n private static Integer DEFAULT_SCALE_VALUE = 4;\n\n @Override\n public void execute(Map<String, Object> methodContext) throws BusinessException {\n Date startDate = new Date();\n log.debug(\"EXECUTE methodContext {}\", methodContext);\n try{\n XMLInvoiceCreator xmlInvoiceCreator = (XMLInvoiceCreator) methodContext.get(\"XMLInvoiceCreator\");\n Invoice invoice = (Invoice) methodContext.get(Script.CONTEXT_ENTITY);\n\n CustomerAccount customerAccount = invoice.getBillingAccount().getCustomerAccount();\n\n Boolean isVirtual = (Boolean) methodContext.get(\"isVirtual\");\n\n Document document = xmlInvoiceCreator.createDocument(invoice,isVirtual.booleanValue());\n\n // Add Tag IBAN to Invoice Element\n addIban(customerAccount, document);\n\n // Modify the detail lines\n modifyConsumptionsData(document, invoice);\n\n // InvoiceLines List\n Element invoiceTag = (Element)document.getElementsByTagName(\"invoice\").item(0);\n Element invoiceLines = document.createElement(\"invoiceLines\");\n addSubscriptionLinesToInvoiceLinesList(invoice, invoiceLines, document);\n addConsumptionLinesToInvoiceLinesList(invoice, invoiceLines, document);\n addOneShotLinesToInvoiceLinesList(invoice, invoiceLines, document);\n invoiceTag.appendChild(invoiceLines);\n\n // Remove the Subscriptions categories\n // removeSubscriptionsCategories(document);\n\n File file = xmlInvoiceCreator.createFile(document,invoice);\n methodContext.put(Script.RESULT_VALUE, file);\n }catch(Exception e){\n throw new BusinessException(e.getMessage());\n }\n printScriptTime(startDate);\n }\n\n private static void printScriptTime(Date startDate) {\n Date endDate = new Date();\n log.warn(\"Script duration {} ms\", endDate.getTime() - startDate.getTime());\n }\n\n /**\n * Remove the Subscriptions from the Categories entry inside the details in the XML document.\n * We need this utility to avoid print this sections in the PDF with Jasper.\n * TODO: We are using the filter in the dataset definition: /addressbook/category[@name = \"work\"]/person\n * TODO: We can remove this piece of code if works fine in the test of Monday 9 of September\n *\n * @param document XML invoice document\n */\n private void removeSubscriptionsCategories(Document document) {\n try{\n List<Element> subscriptionCategories = getSubscriptionsFromDocument(document);\n Element sub = subscriptionCategories.get(0);\n Node subCategory = sub.getParentNode();\n Node subCategories = subCategory.getParentNode();\n Node category = subCategories.getParentNode();\n Node categories = category.getParentNode();\n categories.removeChild(category);\n } catch (Exception e) {\n log.warn(\"Exception removing the Subscriptions of the detailed invoice information...\");\n }\n }\n\n /**\n * Return the list of subscriptions associated to this invoice.\n * Get the BillingAccount from the invoice, after the UserAccounts and then the subscriptions of the first UserAccount\n * in our data model can not exist more than one UserAccount by Billing Account\n *\n * @param invoice The invoice instance\n * @return subscriotions List of subscription instances\n */\n private List<Subscription> getSubscriptions(Invoice invoice) {\n List<Subscription> subscriptions = null;\n try{\n subscriptions = invoice.getBillingAccount().getUsersAccounts().get(0).getSubscriptions();\n } catch (Exception e) {\n log.warn(\"Exception getting the subscriptions related with the invoice {}\", invoice.getInvoiceNumber());\n }\n return subscriptions;\n }\n\n /**\n * Return the WalletOperation instance associated to the RatedTransaction\n *\n * @param trans The rated transaction instance\n * @return wallet The wallet operation instance\n */\n private WalletOperation getWalletOperation(RatedTransaction trans) {\n for (WalletOperation wallet : trans.getWalletOperations()) {\n return wallet;\n }\n return null;\n }\n\n private String convertDateToString(Date date) {\n String invoiceDateFormat = paramBean.getProperty(\"invoice.dateFormat\", DEFAULT_DATE_PATTERN);\n return DateUtils.formatDateWithPattern(date, invoiceDateFormat);\n }\n\n private String round(BigDecimal amount, Integer scale) {\n if (amount == null) {\n amount = BigDecimal.ZERO;\n }\n if (scale == null) {\n scale = 2;\n }\n amount = amount.setScale(scale, RoundingMode.HALF_UP);\n\n return amount.toPlainString().replaceAll(\"(\\\\d+)\\\\.(\\\\d+)\", \"$1,$2\");\n }\n\n private void addSubscriptionLinesToInvoiceLinesList(Invoice invoice, Element invoiceLines, Document doc) {\n String lang = invoice.getBillingAccount().getTradingLanguage().getLanguageCode();\n List<WalletOperation> subscriptionWPList = getSubscriptionWPList(invoice);\n for (WalletOperation wp : subscriptionWPList) {\n Element subscriptionDetails = doc.createElement(\"line\");\n subscriptionDetails.setAttribute(\"msidsn\", wp.getSubscription().getDescription());\n subscriptionDetails.setAttribute(\"description\", getServiceDescriptionTranslated(wp.getServiceInstance(), lang));\n subscriptionDetails.setAttribute(\"startDate\", convertDateToString(wp.getStartDate()));\n subscriptionDetails.setAttribute(\"endDate\", convertDateToString(wp.getEndDate()));\n subscriptionDetails.setAttribute(\"amount\", round(wp.getAmountWithoutTax(), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"tax\", round(wp.getTaxPercent(), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"taxAmount\", round(wp.getAmountTax(), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"totalAmount\", round(wp.getAmountWithTax(), DEFAULT_SCALE_VALUE));\n invoiceLines.appendChild(subscriptionDetails);\n }\n }\n\n\n private HashMap<String,HashMap> groupConsumptionsByInvoiceLines(List<WalletOperation> consumptionsWPList) {\n HashMap<String,HashMap> consumptions = new HashMap<String,HashMap>();\n for (WalletOperation wp : consumptionsWPList) {\n String msidsn = wp.getSubscription().getDescription();\n String description = wp.getInvoiceSubCategory().getDescription();\n if (consumptions.containsKey(msidsn)) {\n // Check if description exists\n HashMap<String,HashMap> consumptionLine = consumptions.get(msidsn);\n if (consumptionLine.containsKey(description)) {\n // Sum the amount to the dict\n HashMap<String,BigDecimal> consumptionAmount = consumptionLine.get(description);\n consumptionAmount.put(\"amount\", consumptionAmount.get(\"amount\").add(wp.getAmountWithoutTax()));\n consumptionAmount.put(\"taxAmount\", consumptionAmount.get(\"taxAmount\").add(wp.getAmountTax()));\n consumptionAmount.put(\"totalAmount\", consumptionAmount.get(\"totalAmount\").add(wp.getAmountWithTax()));\n } else {\n HashMap<String,BigDecimal> consumptionAmount = new HashMap<String,BigDecimal>();\n consumptionAmount.put(\"amount\", wp.getAmountWithoutTax());\n consumptionAmount.put(\"taxAmount\", wp.getAmountTax());\n consumptionAmount.put(\"totalAmount\", wp.getAmountWithTax());\n consumptionLine.put(description, consumptionAmount);\n }\n } else {\n HashMap<String,BigDecimal> consumptionAmount = new HashMap<String,BigDecimal>();\n consumptionAmount.put(\"amount\", wp.getAmountWithoutTax());\n consumptionAmount.put(\"taxAmount\", wp.getAmountTax());\n consumptionAmount.put(\"totalAmount\", wp.getAmountWithTax());\n HashMap<String,HashMap> consumptionLine = new HashMap<String,HashMap>();\n consumptionLine.put(description, consumptionAmount);\n consumptions.put(msidsn, consumptionLine);\n }\n }\n return consumptions;\n }\n\n private void addConsumptionLinesToInvoiceLinesList(Invoice invoice, Element invoiceLines, Document doc) {\n HashMap<String,HashMap> consumptionsAsInvoiceLines = groupConsumptionsByInvoiceLines(getConsumptionsWPList(invoice));\n for (String msidsn : consumptionsAsInvoiceLines.keySet()) {\n HashMap<String,HashMap> consumptionsAsInvoiceLinesByMsidsn = consumptionsAsInvoiceLines.get(msidsn);\n for (String description : consumptionsAsInvoiceLinesByMsidsn.keySet()) {\n HashMap<String,BigDecimal> consumptionAmounts = consumptionsAsInvoiceLinesByMsidsn.get(description);\n Element subscriptionDetails = doc.createElement(\"line\");\n subscriptionDetails.setAttribute(\"msidsn\", msidsn);\n subscriptionDetails.setAttribute(\"description\", description);\n subscriptionDetails.setAttribute(\"startDate\", \"\");\n subscriptionDetails.setAttribute(\"endDate\", \"\");\n subscriptionDetails.setAttribute(\"amount\", round(consumptionAmounts.get(\"amount\"), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"tax\", \"21.0000\");\n subscriptionDetails.setAttribute(\"taxAmount\", round(consumptionAmounts.get(\"taxAmount\"), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"totalAmount\", round(consumptionAmounts.get(\"totalAmount\"), DEFAULT_SCALE_VALUE));\n invoiceLines.appendChild(subscriptionDetails);\n }\n }\n }\n\n private void addOneShotLinesToInvoiceLinesList(Invoice invoice, Element invoiceLines, Document doc) {\n List<WalletOperation> consumptionsWPList = getOneShotsWPList(invoice);\n for (WalletOperation wp : consumptionsWPList) {\n Element subscriptionDetails = doc.createElement(\"line\");\n subscriptionDetails.setAttribute(\"msidsn\", wp.getSubscription().getDescription());\n subscriptionDetails.setAttribute(\"description\", wp.getChargeInstance().getChargeTemplate().getDescription());\n subscriptionDetails.setAttribute(\"startDate\", convertDateToString(wp.getOperationDate()));\n subscriptionDetails.setAttribute(\"endDate\", convertDateToString(wp.getEndDate()));\n subscriptionDetails.setAttribute(\"amount\", round(wp.getAmountWithoutTax(), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"tax\", round(wp.getTaxPercent(), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"taxAmount\", round(wp.getAmountTax(), DEFAULT_SCALE_VALUE));\n subscriptionDetails.setAttribute(\"totalAmount\", round(wp.getAmountWithTax(), DEFAULT_SCALE_VALUE));\n invoiceLines.appendChild(subscriptionDetails);\n }\n }\n\n private List<WalletOperation> getOneShotsWPList(Invoice invoice) {\n List<RatedTransaction> ratedTransactions = invoice.getRatedTransactions();\n List<WalletOperation> wpList = new ArrayList<>();\n for (RatedTransaction trans : ratedTransactions) {\n WalletOperation wp = getWalletOperation(trans);\n if (wp.getInvoiceSubCategory().getCode().contains(\"OSO\")) {\n wpList.add(wp);\n }\n }\n return wpList;\n }\n\n private List<WalletOperation> getConsumptionsWPList(Invoice invoice) {\n List<RatedTransaction> ratedTransactions = invoice.getRatedTransactions();\n List<WalletOperation> wpList = new ArrayList<>();\n for (RatedTransaction trans : ratedTransactions) {\n WalletOperation wp = getWalletOperation(trans);\n if (wp.getInvoiceSubCategory().getCode().contains(\"CONSUMPTION\") && wp.getAmountWithoutTax().compareTo(new BigDecimal(\"0\")) > 0) {\n wpList.add(wp);\n }\n }\n return wpList;\n }\n\n private List<WalletOperation> getSubscriptionWPList(Invoice invoice) {\n List<RatedTransaction> ratedTransactions = invoice.getRatedTransactions();\n List<WalletOperation> wpList = new ArrayList<>();\n for (RatedTransaction trans : ratedTransactions) {\n WalletOperation wp = getWalletOperation(trans);\n if (wp.getInvoiceSubCategory().getCode().contains(\"SUBSCRIPTION\")) {\n wpList.add(wp);\n }\n }\n return wpList;\n }\n\n /**\n * Add service description (translated) to the consumption data,\n * selecting it from the subscription object.\n *\n * @param consumption element with the consumption data to add the service tag and value\n * @param subscriptions list of subscriptions to search the ones that match with the consumption subscription\n * @param lang String with the invoice language: ESP or CAT\n * @return Void\n */\n private void addServiceToConsumption(Element consumption, List<Subscription> subscriptions, String lang) {\n log.debug(\"Setting service...\");\n consumption.setAttribute(\"service\", extractServiceFromSubscriptionAndEDR(consumption, subscriptions, lang));\n }\n\n /**\n * Add msidsn to the consumption data, The msidsn is the line associated to the subscription.\n * We extract it from the EDR information\n *\n * @param consumption element with the consumption data to add the msidsn tag and value\n * @return Void\n */\n private void addMsidsnToConsumption(Element consumption) {\n log.debug(\"Setting msidsn...\");\n Element edr = (Element) consumption.getElementsByTagName(\"edr\").item(0);\n String msidsn = edr.getAttribute(\"accessCode\");\n consumption.setAttribute(\"msidsn\", msidsn);\n }\n\n /**\n * Create and return the HashMap with the data of the data consumption.\n *\n * @param consumption Element of the invoice document with the consumption data\n * @return dataConsumptionByDay HashMap with the consumption relevant information\n */\n private HashMap<String, Object> createDataConsumptionByDay(Element consumption) {\n String to = \"\";\n String msidsn = consumption.getAttribute(\"msidsn\");\n String service = consumption.getAttribute(\"service\");\n String param3 = consumption.getAttribute(\"param3\");\n String param2 = consumption.getAttribute(\"param2\");\n Double quantity = Double.valueOf(consumption.getElementsByTagName(\"quantity\").item(0).getTextContent());\n Double amount = Double.valueOf(consumption.getElementsByTagName(\"amountWithoutTax\").item(0).getTextContent());\n\n HashMap<String,Object> dateConsumptionGroup = new HashMap<>();\n dateConsumptionGroup.put(\"to\", to);\n dateConsumptionGroup.put(\"msidsn\", msidsn);\n dateConsumptionGroup.put(\"service\", service);\n dateConsumptionGroup.put(\"param2\", param2);\n dateConsumptionGroup.put(\"param3\", param3);\n dateConsumptionGroup.put(\"quantity\", quantity);\n dateConsumptionGroup.put(\"amount\", amount);\n\n return dateConsumptionGroup;\n }\n\n /**\n * Get the map with the data consumptions groupped by day and update the information with the consumption\n * record passed as an argument.\n *\n * @param dataConsumptions Map with the data consumptions groupped by date.\n * @param consumption Element of the invoice document with the consumption data.\n */\n private void updateDataConsumptionByDay(HashMap<String,HashMap> dataConsumptionsByDay, Element consumption) {\n String date = consumption.getElementsByTagName(\"usageDate\").item(0).getTextContent();\n if (dataConsumptionsByDay.containsKey(date)) {\n // Update the quantity and the amount of the DataConsumptionByDay\n HashMap<String,Object> dateConsumptionGroup = dataConsumptionsByDay.get(date);\n Double quantity = Double.valueOf(consumption.getElementsByTagName(\"quantity\").item(0).getTextContent());\n Double amount = Double.valueOf(consumption.getElementsByTagName(\"amountWithoutTax\").item(0).getTextContent());\n dateConsumptionGroup.put(\"quantity\", Double.sum((Double) dateConsumptionGroup.get(\"quantity\"), quantity));\n dateConsumptionGroup.put(\"amount\", Double.sum((Double) dateConsumptionGroup.get(\"amount\"), amount));\n } else {\n dataConsumptionsByDay.put(date, createDataConsumptionByDay(consumption));\n }\n }\n\n /**\n * Group the data consumptions by date to print grouped in the invoice.\n * Remove the old entries of data consumptions and add the new records with the amount and the quantity\n * attributes sumed by date.\n *\n * @param document The document generated with the invoice data.\n * @param invoiceNumber The invoice number to report an error if exists.\n */\n private void groupDataConsumptionsByDate(Document document, String invoiceNumber) {\n List<Element> dataConsumptions = getDataConsumptionsFromDocument(document);\n Node dataConsumptionsParent = null;\n try{\n dataConsumptionsParent = dataConsumptions.get(0).getParentNode();\n } catch (Exception e) {\n log.warn(\"The invoice {} does not have consumptions associated\", invoiceNumber);\n return;\n }\n HashMap<String,HashMap> dataConsumptionsByDay = new HashMap<String,HashMap>();\n for (Element consumption : dataConsumptions) {\n updateDataConsumptionByDay(dataConsumptionsByDay, consumption);\n dataConsumptionsParent.removeChild(consumption);\n }\n for (String date : dataConsumptionsByDay.keySet()) {\n dataConsumptionsParent.appendChild(constructDataConsumptionLine(dataConsumptionsByDay.get(date), date, document));\n }\n }\n\n /**\n * Modify the consumptions entries of the invoice document:\n * * Add Service description\n * * Add msidsn\n * * Group the data consumptions by date\n *\n * @param subscrioptions List of subscriptions objects active in this invoice.\n * @param document The document generated with the invoice data.\n */\n private void modifyConsumptionsData(Document document, Invoice invoice) {\n String lang = invoice.getBillingAccount().getTradingLanguage().getLanguageCode();\n List<Subscription> subscriptions = getSubscriptions(invoice);\n List<Element> consumptions = getConsumptionsFromDocument(document);\n for (Element consumption : consumptions) {\n log.debug(\"Consumption: {}\", consumption);\n addServiceToConsumption(consumption, subscriptions, lang);\n addMsidsnToConsumption(consumption);\n log.debug(\"Service set as attribute!!\");\n }\n\n // Group Data consumptions by date\n groupDataConsumptionsByDate(document, invoice.getInvoiceNumber());\n }\n\n private Element constructDataConsumptionLine(HashMap<String, Object> rawDataConsumption, String date, Document document) {\n Element dataConsumptionElement = document.createElement(\"line\");\n\n Element usageDate = document.createElement(\"usageDate\");\n usageDate.setTextContent(date);\n dataConsumptionElement.appendChild(usageDate);\n\n Element quantity = document.createElement(\"quantity\");\n quantity.setTextContent(String.valueOf(rawDataConsumption.get(\"quantity\")));\n dataConsumptionElement.appendChild(quantity);\n\n Element amountWithoutTax = document.createElement(\"amountWithoutTax\");\n amountWithoutTax.setTextContent(String.valueOf(rawDataConsumption.get(\"amount\")));\n dataConsumptionElement.appendChild(amountWithoutTax);\n\n Element edr = document.createElement(\"edr\");\n edr.setAttribute(\"accessCode\", (String) rawDataConsumption.get(\"msidsn\"));\n edr.setAttribute(\"subscription\", (String) rawDataConsumption.get(\"msidsn\"));\n edr.setAttribute(\"eventDate\", date.replace(\"/\", \"-\"));\n edr.setAttribute(\"parameter2\", (String) rawDataConsumption.get(\"param2\"));\n edr.setAttribute(\"parameter3\", (String) rawDataConsumption.get(\"to\"));\n edr.setAttribute(\"parameter5\", date.replace(\"/\", \"-\"));\n edr.setAttribute(\"parameter6\", \"00:00:00\");\n dataConsumptionElement.appendChild(edr);\n\n dataConsumptionElement.setAttribute(\"service\", (String) rawDataConsumption.get(\"service\"));\n dataConsumptionElement.setAttribute(\"msidsn\", (String) rawDataConsumption.get(\"msidsn\"));\n dataConsumptionElement.setAttribute(\"param2\", (String) rawDataConsumption.get(\"param2\"));\n\n\n return dataConsumptionElement;\n }\n\n /**\n * Return the service description in the language passed as argument.\n * In the version 9.0 of OC, the Service description will be translatable, but now it isn't.\n * We use a CustomField to save the label in catalan and in spanish and use the language passed\n * as argument to return the correct label located.\n *\n * @param subscription Subscription instance\n * @param lang String with the language code: ESP or CAT\n * @return service String with the service label translated.\n */\n private String getServiceDescriptionFromSubscription(Subscription subscription, String lang) {\n String serviceDescription = \"\";\n ServiceInstance service = null;\n try{\n service = subscription.getServiceInstances().get(0);\n }catch(Exception e){\n log.error(\"Error retrieving the service description code of the subscription {} with language {}\", subscription.getCode(), lang);\n }\n return getServiceDescriptionTranslated(service, lang);\n }\n\n /**\n * Return the service description in the language passed as argument.\n * In the version 9.0 of OC, the Service description will be translatable, but now it isn't.\n * We use a CustomField to save the label in catalan and in spanish and use the language passed\n * as argument to return the correct label located.\n *\n * @param subscription Subscription instance\n * @param lang String with the language code: ESP or CAT\n * @return service String with the service label translated.\n */\n private String getServiceDescriptionTranslated(ServiceInstance service, String lang) {\n String serviceDescription = \"\";\n String service_lang_label = getCFServiceTranslatedLabel(lang);\n try{\n serviceDescription = service.getServiceTemplate().getCfValues().getValuesByCode().get(service_lang_label).get(0).getStringValue();\n } catch (Exception e){\n log.error(\"Error retrieving the service description code of the service {} with language {}\", service.getCode(), lang);\n }\n return serviceDescription;\n }\n\n /**\n * Return a string with the label of the Service description translation.\n *\n * @param lang String with the language code: ESP or CAT\n * @return service_lang_label String with the service label to get the correct translation from the CFs of Service.\n */\n private String getCFServiceTranslatedLabel(String lang) {\n String service_lang_label = \"CF_LANGUAGE_CAT\";\n if (lang.equals(\"ESP\")) {\n service_lang_label = \"CF_LANGUAGE_ES\";\n }\n return service_lang_label;\n }\n\n private String extractServiceFromSubscriptionAndEDR(Element consumption, List<Subscription> subscriptions, String lang) {\n Element edr = (Element) consumption.getElementsByTagName(\"edr\").item(0);\n log.debug(\"EDR: {}\", edr);\n String subscriptionCode = edr.getAttribute(\"subscription\");\n for (Subscription sub : subscriptions) {\n log.debug(\"Subscription Code: {} is equals to EDR subscription code: {}\", sub.getDescription(), subscriptionCode);\n if (sub.getDescription().equals(subscriptionCode)) {\n return getServiceDescriptionFromSubscription(sub, lang);\n }\n }\n return \"\";\n }\n\n private List<Element> getSubscriptionsFromDocument(Document document) {\n return getLinesBySubCategory(document, \"SUBSCRIPTION\");\n }\n\n private List<Element> getConsumptionsFromDocument(Document document) {\n return getLinesBySubCategory(document, \"CONSUMPTION\");\n }\n\n private List<Element> getDataConsumptionsFromDocument(Document document) {\n return getLinesBySubCategory(document, \"CONSUMPTION_DATA\");\n }\n\n /**\n * Get subCategories elements of the document and return a list with these elements.\n *\n * @param document Document of the invoice.\n * @param subCat String with the subCategory code to search the elements.\n * @return line List of Element instances inside the subCategory.\n */\n private List<Element> getLinesBySubCategory(Document document, String subCat) {\n Element detailTag = (Element) document.getElementsByTagName(\"detail\").item(0);\n int totalCategories = detailTag.getElementsByTagName(\"subCategory\").getLength();\n List<Element> lines = new ArrayList<>();\n for (int i=0; i < totalCategories; i++) {\n Element subCategoryTag = (Element) detailTag.getElementsByTagName(\"subCategory\").item(i);\n if (subCategoryTag.getAttribute(\"code\").contains(subCat)) {\n NodeList nodeLines = (NodeList) subCategoryTag.getElementsByTagName(\"line\");\n int lenghtNodeLines = nodeLines.getLength();\n for (int x=0; x < lenghtNodeLines; x++) {\n lines.add((Element) nodeLines.item(x));\n }\n }\n }\n return lines;\n }\n\n /**\n * Add iban tag to the XML and add the IBAN number as argument\n *\n * @param ca CustomerAccount instances of the invoice\n * @param document Document of the invoice\n */\n private void addIban(CustomerAccount ca, Document document) {\n Element invoiceTag = (Element)document.getElementsByTagName(\"invoice\").item(0);\n Element ibanTag = document.createElement(\"iban\");\n ibanTag.setAttribute(\"number\", getIban(ca));\n invoiceTag.appendChild(ibanTag);\n }\n\n /**\n * Extract the IBAN from the CustomerAccount. The PaymentMethod need be cast to DDPaymentMEthod.\n * If this cast fails, return an empty string and log as warning the error catched.\n *\n * @param ca CustomerAccount instances of the invoice\n * @param document Document of the invoice\n */\n private String getIban(CustomerAccount ca) {\n log.debug(\"Getting the preferredPaymentMethod...\");\n PaymentMethod paymentMethod = ca.getPreferredPaymentMethod();\n paymentMethod = PersistenceUtils.initializeAndUnproxy(paymentMethod);\n String iban = \"\";\n if (paymentMethod != null) {\n if (paymentMethod.getPaymentType() == PaymentMethodEnum.DIRECTDEBIT) {\n if (((DDPaymentMethod) paymentMethod).getBankCoordinates() != null) {\n iban = ((DDPaymentMethod) paymentMethod).getBankCoordinates().getIban();\n }\n }\n }\n return iban;\n }\n}\n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment