Skip to content

Instantly share code, notes, and snippets.

@alefcarlos
Created June 12, 2019 04:48
Show Gist options
  • Save alefcarlos/07eccb24b1ffe75f24761ed8a0f416ad to your computer and use it in GitHub Desktop.
Save alefcarlos/07eccb24b1ffe75f24761ed8a0f416ad to your computer and use it in GitHub Desktop.
var admin = require('firebase-admin');
var Excel = require('exceljs');
var serviceAccount = require(`${__dirname}/key.json`);
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://log-controller.firebaseio.com'
});
var defaultDatabase = admin.firestore();
console.log('até aqui, ok kkkk');
async function getDocks() {
var docks = await defaultDatabase.collection('/companies/QJjGk7HG6wD0AVO94yqt/docks').listDocuments();
var result = docks.map(async (ref) => {
let data = await ref.get();
console.log(`Lendo doca... ${data.id}`);
var fields = data.data();
return {
dockId: data.id,
code: fields.code,
description: fields.description
};
});
return Promise.all(result);
}
async function getEvents() {
var events = await defaultDatabase.collection('/companies/QJjGk7HG6wD0AVO94yqt/events').listDocuments();
var result = events.map(async (ref) => {
let data = await ref.get();
console.log(`Lendo evento... ${data.id}`);
var fields = data.data();
var eventChanges = await getChanges(data.id);
return {
eventId: data.id,
dockId: fields.dockId,
arrivedDate: fields.arrivedDate.toDate(),
driverName: fields.driverName,
itemsQuantity: fields.itemsQuantity,
loadType: fields.loadType,
nfCode: fields.nfCode,
state: fields.state,
type: fields.type,
weight: fields.weight,
changes: eventChanges
};
});
return Promise.all(result);
}
async function getChanges(eventId) {
var changes = await defaultDatabase.collection(`/companies/QJjGk7HG6wD0AVO94yqt/events/${eventId}/changes`).listDocuments();
var result = changes.map(async (ref) => {
let data = await ref.get();
console.log(`Lendo change... ${data.id}`);
var fields = data.data();
return {
eventId: eventId,
reason: fields.reason,
time: fields.time.toDate(),
oldState: fields.fromState,
newState: fields.toState
};
});
return Promise.all(result);
}
async function run() {
var docks = await getDocks();
var events = await getEvents();
console.log('deixando bonito o negócio:');
var data = events.reduce((acc, current) => {
const dock = getDock(docks, current.dockId);
const rows = current.changes.map((change) => {
return {
eventId: current.eventId,
dockId: current.dockId,
dockDescription: dock.description,
arrivedDate: current.arrivedDate,
driverName: current.driverName,
itemsQuantity: current.itemsQuantity,
loadType: current.loadType,
loadTypeDescription: getLoadDescription(current.loadType),
nfCode: current.nfCode,
currentState: current.state,
currentStateDescription: getState(current.state),
type: current.type,
typeDescription: current.type == 0 ? 'Carga' : 'Descarga',
weight: current.weight,
stateChangedReason: change.reason,
stateChangedReasonDescription: getReason(change.reason),
stateChangedTime: change.time,
oldState: change.oldState,
oldStateDescription: getState(change.oldState),
newState: change.newState,
newStateDescription: getState(change.newState)
};
});
return [...acc, ...rows];
}, []);
console.log('Gerando xlsx...');
await createExcel(data);
}
function getReason(reason) {
var reasons = { "0": "Falta de paleteiro", "1": "Falta de rack", "2": "Falta de conferente", "3": "Queda de sistema", "4": "Outros" };
if (reason == null)
return '';
return reasons[reason];
}
async function createExcel(data) {
var workbook = new Excel.Workbook();
workbook.properties.date1904 = true;
var sheet = workbook.addWorksheet('Dados');
//Gerar colunas de acordo com o nome das propriedades
var columns = [];
for (const key in data[0]) {
if (data[0].hasOwnProperty(key)) {
columns.push({ header: key, key: key });
}
}
// Add column headers and define column keys and widths
// Note: these column structures are a workbook-building convenience only,
// apart from the column width, they will not be fully persisted.
sheet.columns = columns;
sheet.addRows(data);
await workbook.xlsx.writeFile(`${__dirname}/dados.xlsx`);
}
function getState(state) {
switch (state) {
case 0:
return 'Criado';
case 1:
return 'Iniciado';
case 2:
return 'Pausado';
case 3:
return 'Encerrado'
default:
break;
}
}
function getDock(docks, dockId) {
return docks.find((dock) => dock.dockId == dockId);
}
function getLoadDescription(loadType) {
switch (loadType) {
case 0:
return 'Pallet';
case 1:
return 'Estivada';
case 2:
return 'Mista'
default:
break;
}
}
run().then(() => {
console.log('tudo ok');
}).catch((e) => {
console.error(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment