Skip to content

Instantly share code, notes, and snippets.

@brunogasparetto
Last active January 30, 2023 19:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunogasparetto/b8f48535c1a0d43a6c6bc418acc22684 to your computer and use it in GitHub Desktop.
Save brunogasparetto/b8f48535c1a0d43a6c6bc418acc22684 to your computer and use it in GitHub Desktop.
Fluig - Exemplo de Gerar e Enviar um PDF à uma pasta GED do Fluig
// Foram usadas as bibliotecas blob-stream e pdfkit
async function generatePdf() {
const usuario = "login",
senha = "senha",
matricula_usuario = 'admin',
pdf = new PDFDocument(),
stream = pdf.pipe(blobStream()),
fileName = 'Nome_Do_Arquivo.pdf',
folderId = await findOrCreateFolderId("nova_pasta");
// criar toda a estrutura do PDF
pdf.text("Olá Mundo!");
pdf.end();
// Ao disparar o evento finish da stream (que vai ocorrer com o pdf.end())
stream.on("finish", function () {
// Envia o arquivo para o WS do Fluig
fetch(
`/api/public/2.0/contentfiles/upload/?fileName=${fileName}`,
{
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
},
cache: "no-cache",
body: stream.toBlob("application/pdf")
}
).then(function (response) {
if (!response.ok) {
throw "Erro ao enviar o arquivo.";
}
}).then(function () {
// Cria o Documento no GED
let document = {
companyId: WCMAPI.organizationId,
description: fileName,
immutable: true,
parentId: folderId, // ID da pasta onde salvar o PDF
isPrivate: false,
downloadEnabled: true,
attachments: [{
fileName: fileName,
}],
};
return fetch(
"/api/public/ecm/document/createDocument",
{
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8",
},
cache: "no-cache",
body: JSON.stringify(document)
}
)
.then(function (response) {
if (!response.ok) {
throw "Erro ao Salvar documento na Pasta Indicada";
}
return response.json();
})
.then(response => response.content);
});
});
}
/**
* Executa uma chamada SOAP por POST
*
* Chamada SOAP para serviços do Fluig.
*
* @param {string} url
* @param {string} xml
* @returns {Promise} Resolve com um objeto XMLDocument
*/
function makeSoapRequest(url, xml) {
return fetch(url, {
method: "POST",
redirect: "follow",
credentials: "omit",
headers: {
"Content-Type": "text/xml;charset=utf-8"
},
body: xml
})
.then(response => response.text())
.then(xmlText => (new DOMParser())
.parseFromString(xmlText, "text/xml"));
}
/**
* Pega o ID da pasta
*
* Se a pasta não existir ela será criada.
*
* @returns {number}
*/
async function findOrCreateFolderId(folderName) {
const defaultParent = 10; // Pasta raíz onde tudo será salvo
return (await findFolderId(folderName, defaultParent)) || (await createFolder(folderName, defaultParent));
}
/**
* Procura a pasta e retorna seu ID
*
* @param {string} folderName Nome da pasta
* @param {number} parentId Pasta pai
* @returns {number} Caso não encontre retornará 0
*/
async function findFolderId(folderName, parentId) {
const xml = `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.dm.ecm.technology.totvs.com/">
<soapenv:Header/>
<soapenv:Body>
<ws:getSubFolders>
<username>usuario</username>
<password>senha</password>
<colleagueId>matricula_usuario</colleagueId>
<companyId>${WCMAPI.organizationId}</companyId>
<documentId>${parentId}</documentId>
</ws:getSubFolders>
</soapenv:Body>
</soapenv:Envelope>`;
let response = await makeSoapRequest(`${WCMAPI.serverURL}/webdesk/ECMFolderService?wsdl`, xml);
for (let folder of response.getElementsByTagName("item")) {
if (folderName != folder.getElementsByTagName("documentDescription")[0].textContent) {
continue;
}
return parseInt(folder.getElementsByTagName("documentId")[0].textContent);
}
return 0;
}
/**
* Cria uma pasta
*
* @param {string} folderName Nome / Descrição da pasta
* @param {number} parentId
* @returns {number} ID da pasta criada
*/
async function createFolder(folderName, parentId) {
const xml = `<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.dm.ecm.technology.totvs.com/">
<soapenv:Header/>
<soapenv:Body>
<ws:createSimpleFolder>
<username>usuario</username>
<password>senha</password>
<publisherId>matricula_usuario</publisherId>
<companyId>${WCMAPI.organizationId}</companyId>
<parentDocumentId>${parentId}</parentDocumentId>
<documentDescription>${folderName}</documentDescription>
</ws:createSimpleFolder>
</soapenv:Body>
</soapenv:Envelope>`;
const response = await makeSoapRequest(`${WCMAPI.serverURL}/webdesk/ECMFolderService?wsdl`, xml);
return folderId = parseInt(response.getElementsByTagName("documentId")[0].textContent) || 0;
}
@paulornr89
Copy link

@brunogasparetto tu teve alguma experiência utilizando fetch com oauth, pois utiliza para consumir as apis do fluig via rest diferente do teu caso que é com soap, e sempre retorna erro de permissão, mas com o axios funciona normal. Não sei se tu teria algum exemplo do tipo.

@brunogasparetto
Copy link
Author

brunogasparetto commented Jan 25, 2023

@paulornr89 , até hoje não usei OAuth no Fluig.

Eu mexo pouco nele e até agora só temos páginas privadas, então não precisei do REST usado em página pública usando autenticação, afinal nas páginas privadas ele já passa a credencial do usuário logado.

O que já vi foi essa solução explicando como usar dataset em página pública usando $.ajax da JQuery https://github.com/Eliezergimenes/Dataset-pagina-publica-

@paulornr89
Copy link

Obrigado @brunogasparetto, na página pública consegui utilizar, estou com dificuldade em utilizar direto de uma aplicação node que precisa enviar arquivos para o servidor do fluig.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment