Send a new invoice data from Books to local certified solution via API json due local compliance

Send a new invoice data from Books to local certified solution via API json due local compliance

Greetings,  
I hope you are doing well and staying safe.  

Due to local compliance regulations, I am required to issue invoices exclusively using locally certified software, which Zoho Books is not. However, we would like to continue using Zoho Books, so we need to send invoice data to an external certified solution each time a new invoice is issued. This external system should automatically generate a corresponding invoice, essentially mirroring the one created in Zoho Books.  

I have access to the API documentation for the external certified solution and have attempted to create a custom function to extract invoice data, format it in JSON, and send it to the external system. However, due to my limited knowledge, I have been unable to save the custom function successfully, as the Deluge editor consistently flags syntax errors.  

The API documentation for the external solution can be found here: https://api.factplus.co.ao/documentation/  

Below are some of the approaches I have attempted:  

===
void EnviarFctraParaFctpls( Map invoice, Map organization, Map user )
{
    // A função já recebe os detalhes da fatura e organização como 'invoice' e 'organization'
    // Não precisamos usar zoho.books.getRecordsByID para os dados básicos da fatura.
    // Usaremos 'invoice' diretamente.

    // 1. Extrair Detalhes da Fatura (diretamente do 'invoice' Map)
    invoiceData = invoice; // 'invoice' já é o mapa com os dados da fatura
    organizationId = organization.get("organization_id"); // ID da sua organização no Zoho Books

    invoiceNumber = invoiceData.get("invoice_number");
    invoiceDate = invoiceData.get("date"); // Formato 'YYYY-MM-DD'
    dueDate = invoiceData.get("due_date"); // Formato 'YYYY-MM-DD'
    reference = invoiceData.get("reference_number"); // Pode usar o número de referência do Zoho Books
    currency = invoiceData.get("currency_code");
    // observation = invoiceData.get("notes"); // Supondo que 'notes' seja para observações
    
    // ATENÇÃO: Verifique na documentação do Factplus como lidar com 'retention'.
    // Se o Zoho Books não tiver um campo direto para 'retention', você pode precisar de lógica extra
    // ou definir como "0" se não for aplicável no seu caso.
    retention_value = "0"; 
    
    // Dados do Cliente
    customerData = invoiceData.get("customer_details");
    clientName = customerData.get("customer_name");
    clientNIF = customerData.get("vat_reg_no"); // Assumindo que NIF seja o VAT Registration Number
    clientEmail = customerData.get("email");
    clientCity = customerData.get("city");
    clientAddress = customerData.get("billing_address").get("address"); // Endereço de fatura
    clientPostalCode = customerData.get("billing_address").get("zip"); // CEP de fatura
    clientCountry = customerData.get("billing_address").get("country"); // País de fatura

    // Itens da Fatura
    lineItems = invoiceData.get("line_items");
    factplusItems = collection(); // Coleção para armazenar os itens formatados para o Factplus

    for each item in lineItems
    {
        // Para itemcode, é ideal usar um ID que seja único e identificável no Factplus.
        // item.get("item_id") é o ID interno do Zoho Books, o que pode não ser ideal se o Factplus
        // espera um código de item de produto/serviço. Considere usar item.get("name") ou um campo personalizado.
        itemCode = item.get("item_id"); 
        description = item.get("description");
        price = item.get("rate");
        quantity = item.get("quantity");
        taxRate = item.get("tax_percentage"); // Taxa de imposto
        discount = item.get("discount"); // Desconto por linha de item
        
        // ATENÇÃO: exemption_code e retention por item precisam ser verificados na API do Factplus.
        exemptionCode = ""; // Valor padrão, ajuste se tiver campo correspondente
        itemRetention = "0"; // Valor padrão, ajuste se tiver campo correspondente

        factplusItem = Map();
        factplusItem.put("itemcode", itemCode);
        factplusItem.put("description", description);
        factplusItem.put("price", price);
        factplusItem.put("quantity", quantity);
        factplusItem.put("tax", taxRate);
        factplusItem.put("discount", discount);
        factplusItem.put("exemption_code", exemptionCode);
        factplusItem.put("retention", itemRetention);
        
        factplusItems.add(factplusItem);
    }
    
    // 2. Construir o Objeto JSON para a API do Factplus
    // ATENÇÃO: SUBSTITUA 'SUA_CHAVE_API_AQUI' PELA SUA CHAVE DE 32 DÍGITOS DO FACTPLUS
    factplusPayload = Map();
    factplusPayload.put("apicall", "CREATE");
    factplusPayload.put("apikey", "SUA_CHAVE_API_AQUI"); // <-- SUA CHAVE API DO FACTPLUS AQUI!

    documentMap = Map();
    documentMap.put("type", "factura"); // Tipo de documento, confirme se "factura" é o correto
    documentMap.put("date", invoiceDate);
    documentMap.put("duedate", dueDate);
    documentMap.put("vref", invoiceNumber); // Usando o número da fatura como referência. Verifique se o Factplus aceita este formato.
    // A "serie" é crucial. O exemplo do Factplus mostra "2020". Você precisa definir uma série apropriada.
    // Se o Zoho Books não tiver um campo para série, pode ser um valor fixo ou derivado.
    documentMap.put("serie", "2024"); // <-- ATENÇÃO: Defina a série correta para o Factplus (ex: "2024", "FS_A")
    documentMap.put("currency", currency);
    documentMap.put("exchange_rate", "0"); // Ajuste se houver taxa de câmbio
    // documentMap.put("observation", invoiceData.get("notes")); // Se usar campo de notas
    documentMap.put("retention", retention_value);

    clientMap = Map();
    clientMap.put("name", clientName);
    clientMap.put("nif", clientNIF);
    clientMap.put("email", clientEmail);
    clientMap.put("city", clientCity);
    clientMap.put("address", clientAddress);
    clientMap.put("postalcode", clientPostalCode);
    clientMap.put("country", clientCountry);
    
    factplusPayload.put("document", documentMap);
    factplusPayload.put("client", clientMap);
    factplusPayload.put("items", factplusItems);

    // Converter o mapa Deluge para string JSON
    jsonString = factplusPayload.toString();

    // 3. Fazer a Chamada HTTP POST para a API do Factplus
    // ATENÇÃO: Você PRECISA substituir "https://api.factplus.co.ao" pelo ENDPOINT COMPLETO
    // da API do Factplus para a criação de faturas.
    // Ex: "https://api.factplus.co.ao/v1/invoices" ou similar.
    factplusAPI_URL = "https://api.factplus.co.ao"; // <-- SUBSTITUIR PELO ENDPOINT ESPECÍFICO DE CRIAÇÃO DE FATURA

    // Cabeçalhos (Content-Type é essencial para JSON)
    headers = Map();
    headers.put("Content-Type", "application/json");

    // Executar a chamada API
    apiResponse = invokeurl
    [
        url : factplusAPI_URL
        type : POST
        headers: headers
        content : jsonString
    ];

    // 4. Tratar a Resposta da API
    info "Request sent to Factplus: " + jsonString; // Para depuração, mostre o que foi enviado
    info "Factplus API Response: " + apiResponse;

    // Adicione lógica para verificar a resposta aqui.
    // Ex: if (apiResponse.get("status") == "success") { ... }
    // ou if (apiResponse.get("code") == 200) { ... }
    // Logar erros se a resposta indicar falha e talvez enviar um email de alerta.
    if (apiResponse.get("status") == "success") // Supondo que a API retorne um campo 'status'
    {
        info "Fatura enviada com sucesso para o Factplus!";
        // Opcional: Atualizar a fatura no Zoho Books com um campo de status "Enviado para Factplus"
        // Ou armazenar o ID de retorno do Factplus.
    }
    else
    {
        error "Erro ao enviar fatura para o Factplus: " + apiResponse.get("message"); // Supondo campo 'message'
        // Opcional: Enviar email de erro para o cliente ou para o administrador
    }
}
===

And

===
// Função para enviar fatura do Zoho Books para o Factplus
// Parâmetro: invoice_id (ID da fatura criada)
invoice_id = input.invoice_id;

// Obter detalhes da fatura do Zoho Books
invoice = zoho.books.getRecordsByID("Invoices", organization_id, invoice_id);
invoice_data = invoice.get("invoice");

// Mapear dados do cliente
customer_id = invoice_data.get("customer_id");
customer = zoho.books.getRecordsByID("Contacts", organization_id, customer_id);
customer_data = customer.get("contact");
client_map = Map();
client_map.put("name", customer_data.get("contact_name"));
client_map.put("nif", customer_data.get("tax_reg_no", ""));
client_map.put("email", customer_data.get("email", ""));
client_map.put("city", customer_data.get("billing_address").get("city", ""));
client_map.put("address", customer_data.get("billing_address").get("address", ""));
client_map.put("postalcode", customer_data.get("billing_address").get("zip", ""));
client_map.put("country", customer_data.get("billing_address").get("country", "Angola"));

// Mapear itens da fatura
items_list = List();
for each item in invoice_data.get("line_items")
{
    item_map = Map();
    item_map.put("itemcode", item.get("item_id", "ITEM" + item.get("line_item_id")));
    item_map.put("description", item.get("name"));
    item_map.put("price", item.get("rate").toString());
    item_map.put("quantity", item.get("quantity").toString());
    item_map.put("tax", "14"); // Ajuste conforme a tributação aplicável
    item_map.put("discount", item.get("discount", "0").toString());
    item_map.put("exemption_code", "");
    item_map.put("retention", "");
    item_map.put("unit", "Unidade");
    items_list.add(item_map);
}

// Construir o corpo da requisição para o Factplus
payload = Map();
payload.put("apicall", "CREATE");
payload.put("apikey", "SUA_CHAVE_API_FACTPLUS"); // Substitua pela sua chave de API
document_map = Map();
document_map.put("type", "factura");
document_map.put("date", invoice_data.get("date"));
document_map.put("duedate", invoice_data.get("due_date"));
document_map.put("vref", invoice_data.get("invoice_number"));
document_map.put("serie", invoice_data.get("date").left(4)); // Ano da fatura
document_map.put("currency", "AOA");
document_map.put("exchange_rate", "0");
document_map.put("observation", "");
document_map.put("retention", "0");
payload.put("document", document_map);
payload.put("client", client_map);
payload.put("items", items_list);

// Enviar requisição para o Factplus
headers = Map();
headers.put("Content-Type", "application/json");
response = invokeurl
[
    type: POST,
    parameters: payload.toString(),
    headers: headers,
    connection: "FactplusAPI"
];

// Logar a resposta para depuração
info response;
===

Any help?
Thanks in advance.
    • Recent Topics

    • Mass Print Attachments from Selected Records in Custom Module

      Dear Zoho CRM Team, We’d like to request a feature enhancement regarding the handling of attachments. Use Case: We have a custom module that stores invoices uploaded by our affiliates. Currently, we need to open each record individually to print these
    • CRM x WorkDrive: File storage for new CRM signups is now powered by WorkDrive

      Availability Editions: All DCs: All Release plan: Released for new signups in all DCs. It will be enabled for existing users in a phased manner in the upcoming months. Help documentation: Documents in Zoho CRM Manage folders in Documents tab Manage files
    • Experience effortless record management in CRM For Everyone with the all-new Grid View!

      Hello Everyone, Hope you are well! As part of our ongoing series of feature announcements for Zoho CRM For Everyone, we’re excited to bring you another type of module view : Grid View. In addition to Kanban view, List view, Canvas view, Chart view and
    • Introducing more AES digital signature options in Zoho Sign

      Greetings! Zoho Sign has continually strived to partner with trust service providers across the globe to give you complete security and confidence, so you can e-sign documents no matter where you are. We've recently partnered with IgniSign, a qualified
    • Shuffling between one note to the next

      I usually start all my notes per interaction with a contact with the date and then a little detail. But when I search for it it only see a small portion of the note and can't immediately tell which contact its associated with. can we make the note content
    • Tip #53: Populate and search values from tables using Table Lookup

      Qntrl supports tables to store organization-related data and access it easily. Data stored here can be populated and displayed in orchestration using Table Lookups. This helps organizations list sizeable data in dropdown or multiselect dropdown fields
    • 🇺🇸 🇨🇦 🇲🇽 Ask the Experts: A Live Q&A Session

      We’re back with another exciting edition of the Ask the Experts series—this time exclusively for our Zoho Recruit users from the USA, Canada, and Mexico! Whether you're trying to configure your account better, have burning questions about customization,
    • Important Update: TRAI Mandates New SMS Header Format

      Hello everyone, We have an announcement regarding a new regulation by the Telephone Regulatory Authority of India (TRAI) that affects all application-to-person (A2P) SMS services. Starting on May 6, 2025, TRAI has mandated that telecom service providers
    • Preview generation in progress for days

      I uploaded a video file to Zoho webinar. The file has been showing Preview generation in progress for days. Pls help, why is not approved?
    • Important! ZipRecruiter Sponsored Posting Plan Changes in Zoho Recruit

      Greetings, We’re reaching out to inform you about an important upcoming change to the ZipRecruiter Sponsored job board integration within Zoho Recruit. What’s Changing? Starting June 1, 2025, Zoho Recruit will be updated with ZipRecruiter's latest pricing
    • Recuring bills payments

      I've entered recuring bills that are auto drafted from my account monthly. Can I set up the recuring payment or do I continue to manually do it monthly?
    • Action requested: Retain your sales journey configuration in Path Finder

      Dear Customers, We hope you're well! As you might know, we're completely overhauling our journey management suite, CommandCenter, and are in the last leg of it. As a means of getting ready to go live, we will be announcing a series of requests and updates
    • Zoho Calling

      I would to be able to track my cell phone calls in the CRM.  So if a contact calls my cell phone number, note of that phone call will be made in the CRM so that I don't have to remember to go back in and add the call manually. Is there a way to connect the CRM and my cell phone via a 3rd party? Such as Google Voice, Skype, etc. If not, this would be a great feature. The biggest problem I run into in sales are the calls that where made on my cell phone and never got logged in the CRM.
    • Global Sets for Multi-Select pick lists

      When is this feature coming to Zoho CRM? It would be very useful now we have got used to having it for the normal pick lists.
    • Again about the backlighting of the search query when searching in a client for Linux

      Some time passed, I installed a client for Linux version 3.4.0, but I still did not receive the promised search with the backlighting of the search query how it was implemented in the client for android. In the previous topic, you told me that this function
    • CRM Custom function updating a module record shows the Super Admin user as the record modifier

      Dear Zoho CRM Team, Is there any way to update this so that when a custom function has updated a record the Super Admin user doesn't become the modifier? This happens on the record as a modifier and shows up in the audit logs. It would be more useful
    • Workdrive Upload Notification

      Is there a way to be notified when someone externally has uploaded files to a folder? The "Unread" tab is really worthless because it shows all files from every directory on the system. I just need an email (or bell at worst) that says "someone has uploaded into <foldername>".
    • Zoho Mail not working. Constant OTP

      Firstly, my emails have been playing up for over a year. They are struggling to send and I have to press Send a few time to make them going. They mostly hover with a loading note saying Sending. I emailed Zoho and they got it working, but now it is doing
    • How do I edit the Calendar Invite notifications for Interviews in Recruit?

      I'm setting up the Zoho Recruit Interview Calendar system but there's some notifications I don't have any control over. I've turned off all Workflows and Automations related to the Calendar Scheduling and it seems that it's the notification that is sent
    • Marketer's Space: Bookmarks by Zoho Campaigns

      Hello Marketers, In this week's Marketer's Space, we'll look at a simple yet powerful feature that makes a big difference in your workflow: Bookmarks. Bookmarks is a built-in feature in Zoho Campaigns that enables you to create a personalized library
    • Workflow for "Expenses" module?

      Hi there, over the last 2 years, Zoho Expense has seen tremendous growth and we are happy with it. But, sometimes it is frustrating to see things are being implemented halfheartedly, or so it seems. For example, There is the possibility to create workflows
    • Changing Link Color

      When I create a link from a block of text, the text color changes to a color i do not want. After scrolling through the CSS and HTML files I cannot find the setting for the link color. Changing the link color word by word seems inefficient and must be a setting somewhere? Greg Aanes 2109 Queen Street Bellingha WA USA
    • on submit of creator form then record is create in Zoho crm purchase module then on automatically task want to create in the crm

      on submit of creator form then record is create in Zoho crm purchase module then on automatically task want to create in the crm
    • Allow Mapping of Zoho Desk Knowledge Base Categories to Multiple Departments in Zoho SalesIQ

      Hello Zoho Team, We hope you're doing well. We would like to request an enhancement to the Zoho SalesIQ integration with Zoho Desk, specifically regarding the way Knowledge Base (KB) articles are mapped and displayed across departments. Current Limitation
    • Introducing Forms in Zoho Sheet

      We hereby bring you the power of ​forms in Zoho Sheet. ​Now, build and create your own customized forms using Zoho Sheet. Be it compiling a questionnaire or rolling out a survey, Zoho Sheet can do it all for you. Forms is an excellent feature that helps you collect information in the simplest of ways and having it in Zoho Sheet takes it a notch higher. Build Simple yet Powerful forms Building forms using Zoho Sheet is fairly simple. The exclusive 'Form' tab lets you create one quickly. Whether you
    • Recurring Events Not Appearing in "My Events" and therefore not syncing with Google Apps

      We use the Google Sync functionality for our events, and it appears to have been working fine except: I've created a set of recurring events that I noticed were missing from my Google Apps calendar. Upon further research, it appears this is occurring
    • [Important announcement] Zoho Writer will mandate DKIM configuration for automation users

      Hi all, Effective Dec. 31, 2024, configuring DKIM for From addresses will be mandatory to send emails via Zoho Writer. DKIM configuration allows recipient email servers to identify your emails as valid and not spam. Emails sent from domains without DKIM
    • Desk - CRM Integration: SPAM Contacts (Auto Delete)

      SPAM contacts is a useful feature, but when the CRM sync is used, it is very frustrating. When a contact is marked as SPAM on Desk, I wish to do the same on CRM. When a SPAM contact is deleted, I would like it deleted from CRM. The feature looks half-baked.
    • View Audit Trail field

      The Audit Trail feature is great, but its data is only available to admin users. It would be really great to have a system field "Audit trail" that we can add to the detailed view of a record. This would allow supervisors, directors and etc. to quickly track what changes have been done by whom for each record. It is a current feature from a client of mine and while it's probably possible to hard code it, since this data is already available in Zoho, I would be surprised to hear how hard it would
    • Creator roadmap for the rest of 2022

      Hi everyone, Hope you're all good! Thanks for continuing to make this community engaging and informative. Today we'd like to share with you our plans for the near future of Creator. We always strive to strike a good balance of features and enhancements
    • How do I modify the the incoming/current call popup? I can modify other call pages but not that one.

      I want to modify the incoming and active call popup on the crm to include customer relevant information, such as purchase history or length of relationship. Under modules and fields, I don't seem to see active call as a choice to modify, only the main
    • Announcing new features in Trident for Windows (v.1.27.4.0)

      Hello Community, Trident for Windows is here with exciting new features to elevate your communication and enhance productivity. Let’s dive into what’s new! Smart Sign-in. You can now sign in to Trident with Smart Sign-in. With this new addition, you can
    • Add Lookup Field in Tasks Module

      Hello, I have a need to add a Lookup field in addition to the ones that are already there in the Tasks module. I've seen this thread and so understand that the reason lookup fields may not be part of it is that there are already links to the tables (https://help.zoho.com/portal/en/community/topic/custom-fields-on-task-module).
    • How do I synchronize a quote to an opportunity?

      Hi everyone, We don't quote anything via Zoho but we use it to track services/products so that I can see what was actually sold, vs an opportunity with just shows an amount.  We use the quotes for other purposes, mostly to request a quote from Salesforce but we don't invoice or do sales orders or anything. (Basically a user makes a quick quote in Zoho, adds items and pricing, and then exports to PDF which gets emailed to our Quote Desk who then enters the request into Salesforce). Just wondering
    • Time Entry : Auto fill fields Hours minutes seconds

      Hello world, Do someone know a script (for workflow rules) which fill automatically fields hours spent, minutes spent, seconds spent when we fill Executed time and End time Formula should start from (End time - Executed time) Thx in advance
    • MULTI-SELECT LOOKUP - MAIL TEMPLATE

      Dear all how are you? We need to insert data from MULTI-SELECT LOOKUP in a email template, but I can't do that, when I'm creating the template I can't find the field to insert it. is there any solution? PVU
    • Create Encrypted Zoho Forms URL for SMS Pre-Population forms using zfcrm_entity=

      Hello Zoho Forms Community and Zoho Team, I’m trying to send a Zoho Forms URL via SMS with pre-populated CRM contact data, inspired by a post from four years ago by GlennP (https://help.zoho.com/portal/en/community/topic/passing-the-crm). Our form is
    • Tracking Emails sent through Outlook

      All of our sales team have their Outlook 365 accounts setup with IMAP integration. We're trying to track their email activity that occurs outside the CRM. I can see the email exchanges between the sales people and the clients in the contact module. But
    • Zoho Forms - edit the settings of the Zoho CRM field to change the integration with CRM

      I've created a Zoho CRM field in my form to pre-populate selected CRM details into the form, following the instructions here https://help.zoho.com/portal/en/kb/crm/integrations/zoho/zoho-forms/articles/zoho-forms-crm-integration#Step_2_-_Add_Zoho_CRM_Field_in_the_form
    • Data Integration Platform

      Hi,  Is anyone aware about a data integration platform like Dell Boomi that can work with Zoho Support? Any help will be higghly appreciated.  Thanks Kunal
    • Next Page