Skip to content

Instantly share code, notes, and snippets.

@JeanGoncalves
Last active May 17, 2025 23:15
Show Gist options
  • Select an option

  • Save JeanGoncalves/a740f47edc649882adb413d85d669a6e to your computer and use it in GitHub Desktop.

Select an option

Save JeanGoncalves/a740f47edc649882adb413d85d669a6e to your computer and use it in GitHub Desktop.
/**
* google extension:
* https://chromewebstore.google.com/detail/javascript-injector/knmnopfmccchnnfdoiddbihbcboeedll
*
* gist digisac commands
* https://gist.github.com/JeanGoncalves/a740f47edc649882adb413d85d669a6e
*
* digisac api swagger
* http://digisac-docs.s3-website-us-west-1.amazonaws.com/#/
*
*
* async function loadGistContent() {
* try {
* const response = await fetch('https://gist.githubusercontent.com/JeanGoncalves/a740f47edc649882adb413d85d669a6e/raw');
* const code = await response.text();
* const script = document.createElement('script');
* script.textContent = code;
* document.body.appendChild(script);
* } catch (error) {
* console.error('Erro ao carregar o Gist:', error);
* }
* }
* loadGistContent();
*
*
* close ticket
*
* https://brendi.digisac.co/api/v1/contacts/853b031a-918e-4f04-850d-6c88acf200c5/ticket/close
* {
* "byUserId":"0d966f1e-dc29-4eab-8dd3-95c1c2c51a97",
* "comments":"",
* "ticketTopicIds":["30b1328b-7561-42f2-93fa-df0ffaa107d2"]
* }
*
*/
(function() {
let scriptEnabled = true; // Variável para controlar o estado do script
let menuVisible = false; // Movido para o escopo principal
function selectContact(index, option) {
let contact = document.querySelectorAll('.chatContactDiv');
if (option === 'up' && index === 0) {
contact[contact.length - 1].click();
} else if (option === 'up') {
contact[index - 1].click();
} else if (option === 'down' && index === contact.length - 1) {
contact[0].click();
} else if (option === 'down') {
contact[index + 1].click();
} else {
contact[index].click();
}
}
function insertClientDetails() {
const chatMenuDiv = document.querySelector('[data-testid="chat-menu-aba"]');
if (chatMenuDiv) {
const header = chatMenuDiv.querySelector('header');
const targetDiv = header?.nextElementSibling;
if (targetDiv) {
const helloWorldDiv = document.createElement('div');
helloWorldDiv.className = 'px-3 py-2 mb-2 text-center border-bottom client-details';
targetDiv.insertAdjacentElement('afterend', helloWorldDiv);
}
}
}
function getContactIndex() {
let itemSelected = 0;
let contact = document.querySelectorAll('.chatContactDiv');
contact.forEach((c, idx) => c.classList.contains('bnrZer') ? itemSelected = idx : '');
return itemSelected;
}
async function getContacts(tipo) {
const typeChat = {
include: {
where: {
userId: "0d966f1e-dc29-4eab-8dd3-95c1c2c51a97"
},
},
orderByLastMessage: true,
};
const typeFila = {
include: {
include: ["user"],
model: "currentTicket",
where: {
departmentId: {
"$in": [
"f15bbbf8-f260-48aa-9c19-cebbcf7da9f1",
"76c04478-3917-4343-aee3-74ed0e2c5e54"
]
},
userId: null
},
},
orderByCurrentTicketCreatedAt: true,
};
const payload = {
where: {
visible: true,
accountId: "a6d400ae-4f30-497b-8b61-537a249a26d3"
},
include: [
"avatar",
"thumbAvatar",
{
model: "lastMessage",
include: ["file", "reactionParentMessage"]
}
],
noTag: false,
includeTicketTransfer: true,
offset: 0,
limit: 30
};
try {
if (tipo === 'chat' && payload.include) {
payload.include = [...payload.include, typeChat.include];
payload.orderByLastMessage = typeChat.orderByLastMessage;
} else if (tipo === 'fila' && payload.include) {
payload.include = [...payload.include, typeFila.include];
payload.orderByCurrentTicketCreatedAt = typeFila.orderByCurrentTicketCreatedAt;
}
const response = await fetch(`https://brendi.digisac.co/api/v1/contacts/list?t=${tipo}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, text/plain, */*',
'Authorization': 'Bearer 6c7e57ef90d24ec023902d75271f1f19f5035521',
'Branch': 'default'
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`Status ${response.status}: ${response.statusText}`);
}
const data = await response.json();
return data.data || [];
} catch (error) {
console.error('Erro ao buscar contatos:', error);
return [];
}
}
document.addEventListener('click', async (event) => {
if (event.target.closest('.chatContactDiv')) {
if (!document.querySelector('.client-details')) {
insertClientDetails();
}
const clientDetails = document.querySelector('.client-details');
const previousDiv = clientDetails.previousElementSibling;
const span = previousDiv.querySelector('span');
if (span) {
const spanText = span.textContent;
const matches = spanText.match(/\((.*?)\)/);
clientDetails.innerHTML = '';
if (matches && matches[1]) {
const items = matches[1].split(',');
items.forEach(item => {
const p = document.createElement('p');
p.textContent = item.trim();
clientDetails.appendChild(p);
});
} else {
const p = document.createElement('p');
p.textContent = spanText;
clientDetails.appendChild(p);
}
}
}
});
function toggleScript() {
scriptEnabled = !scriptEnabled;
const indicator = document.querySelector('.script-indicator');
const text = document.querySelector('.script-text');
if (scriptEnabled) {
indicator.style.backgroundColor = '#4CAF50';
indicator.style.boxShadow = '0 0 10px #4CAF50';
text.style.color = '#4CAF50';
} else {
indicator.style.backgroundColor = '#FF0000';
indicator.style.boxShadow = '0 0 10px #FF0000';
text.style.color = '#FF0000';
}
}
async function getConnectionStatus() {
try {
const response = await fetch('https://brendi.digisac.co/api/v1/services', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer 6c7e57ef90d24ec023902d75271f1f19f5035521'
},
body: JSON.stringify({
where: { archivedAt: { $eq: null } },
order: [["name", "asc"]],
page: 1,
perPage: 15
})
});
const data = await response.json();
return data.data || [];
} catch (error) {
console.error('Erro ao buscar status:', error);
return [];
}
}
function createDropdownMenu() {
const menu = document.createElement('div');
menu.className = 'script-menu';
menu.style.cssText = `
position: absolute;
top: 100%;
left: 0;
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
padding: 8px;
min-width: 200px;
display: none;
z-index: 9999;
`;
// Toggle Script Option
const toggleOption = document.createElement('div');
toggleOption.style.cssText = `
padding: 8px;
border-bottom: 1px solid #eee;
display: flex;
align-items: center;
justify-content: space-between;
cursor: pointer;
`;
toggleOption.innerHTML = `
<span>Script Status</span>
<div class="toggle-switch" style="
width: 40px;
height: 20px;
background: ${scriptEnabled ? '#4CAF50' : '#FF0000'};
border-radius: 10px;
position: relative;
cursor: pointer;
">
<div style="
position: absolute;
width: 16px;
height: 16px;
background: white;
border-radius: 50%;
top: 2px;
left: ${scriptEnabled ? '22px' : '2px'};
transition: left 0.2s;
"></div>
</div>
`;
// Connections Status
const connectionsStatus = document.createElement('div');
connectionsStatus.style.cssText = `
padding: 8px;
font-size: 12px;
`;
connectionsStatus.innerHTML = '<div class="connections-list">Carregando conexões...</div>';
menu.appendChild(toggleOption);
menu.appendChild(connectionsStatus);
return menu;
}
function updateConnectionsList(connections) {
const connectionsList = document.querySelector('.connections-list');
if (!connectionsList) return;
connectionsList.innerHTML = connections.map(conn => `
<div style="
display: flex;
align-items: center;
justify-content: space-between;
margin: 4px 0;
">
<span style="font-size: 11px;">${conn.name}</span>
<span style="
width: 8px;
height: 8px;
border-radius: 50%;
background: ${conn.data?.status?.isConnected ? '#4CAF50' : '#FF0000'};
display: inline-block;
"></span>
</div>
`).join('');
}
function init() {
const navbar = document.querySelector('.navbar-collapse .navbar-nav');
if (!navbar) {
console.error('Navbar não encontrada');
return;
}
// Criar container principal como div
const container = document.createElement('div');
container.className = 'sc-krNlru dqZJuH';
container.style.cursor = 'pointer';
// Criar div para coluna com flex
const colDiv = document.createElement('div');
colDiv.className = 'col';
colDiv.style.display = 'flex';
colDiv.style.flexDirection = 'column';
colDiv.style.alignItems = 'center';
// Criar ícone - Script/Código
const iconDiv = document.createElement('div');
iconDiv.innerHTML = `
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M8 16L4 12L8 8" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M16 8L20 12L16 16" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M14 4L10 20" stroke="white" stroke-width="2" stroke-linecap="round"/>
</svg>
`;
// Criar label BRENDI
const label = document.createElement('div');
label.className = 'sc-gmgFlS fvqhvy';
label.textContent = 'BRENDI';
label.style.color = '#FFFFFF';
label.style.backgroundColor = '#4CAF50';
// Criar tooltip com estilo ajustado
const tooltip = document.createElement('div');
tooltip.className = 'tooltipUncontrolled';
tooltip.textContent = 'Script Brendi Ativo';
tooltip.style.fontSize = '12px';
tooltip.style.padding = '4px 8px';
tooltip.style.whiteSpace = 'nowrap';
// Montar estrutura
colDiv.appendChild(iconDiv);
colDiv.appendChild(label);
container.appendChild(colDiv);
container.appendChild(tooltip);
// Inserir como primeiro item
navbar.insertBefore(container, navbar.firstChild);
// Toggle do script
container.addEventListener('click', () => {
scriptEnabled = !scriptEnabled;
label.style.backgroundColor = scriptEnabled ? '#4CAF50' : '#FF0000';
iconDiv.style.opacity = scriptEnabled ? '1' : '0.5';
tooltip.textContent = scriptEnabled ? 'Script Brendi Ativo' : 'Script Brendi Inativo';
});
}
document.addEventListener('keydown', function(event) {
if (!scriptEnabled) return; // Não executa se script desabilitado
// Verifica ESC
if (event.key === 'Escape') {
let cancelar = document.querySelector('[data-testid="cancel-closeTicket"]');
if (!cancelar) return;
cancelar.click();
}
// Verifica ENTER
if (event.key === 'Enter') {
let confirmar = document.querySelector('[data-testid="confirm-closeTicket"]');
if (!confirmar) return;
let index = getContactIndex()
confirmar.click()
setTimeout(() => {
selectContact(index)
}, 800)
}
// meta + e
if (event.metaKey && event.key === 'e') {
event.preventDefault(); // Impede a ação padrão do navegador
let ticket = document.querySelector('[data-testid="chat-button-close_ticket"]');
if (!ticket) return;
ticket.click();
}
// meta + shift + seta pra cima
if (event.metaKey && event.shiftKey && event.key === 'ArrowUp') {
selectContact(getContactIndex(), 'up')
}
// meta + shift + seta pra baixo
if (event.metaKey && event.shiftKey && event.key === 'ArrowDown') {
selectContact(getContactIndex(), 'down')
}
});
function setContactId(contacts) {
const container = document.querySelector('.ReactVirtualized__Grid__innerScrollContainer');
if (container) {
Array.from(container.children).forEach((child, index) => {
child.setAttribute('contactId', contacts[index].id);
});
} else {
console.log('Não foi possível encontrar a lista de contatos');
}
}
setTimeout(init, 1000);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment