You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
72 lines
2.1 KiB
JavaScript
72 lines
2.1 KiB
JavaScript
// Cuenta el número de pedidos y las cantidades solicitadas por cada cliente, así como cuál es su pedido promedio
|
|
//
|
|
// CONSTANTS
|
|
|
|
const ORIGIN_TABLE_NAME = "Abarax España";
|
|
const ORIGIN_VIEW_NAME = "Default";
|
|
|
|
const RESULT_TABLE_NAME = "Clientes"
|
|
const RESULT_VIEW_NAME = "Default";
|
|
|
|
const originClientColumnName = "Cliente";
|
|
const originQuantityColumnName = "Cantidad";
|
|
|
|
const resultClientColumnName = "Cliente";
|
|
const resultCountColumnName = "Pedidos";
|
|
const resultQuantityColumnName = "Cantidad";
|
|
|
|
const originTable = base.getTableByName(ORIGIN_TABLE_NAME);
|
|
const originView = base.getViewByName(originTable, ORIGIN_VIEW_NAME);
|
|
const resultTable = base.getTableByName(RESULT_TABLE_NAME);
|
|
const resultView = base.getViewByName(resultTable, RESULT_VIEW_NAME);
|
|
|
|
// Object to save every reocurring item and its count
|
|
const elements = {};
|
|
|
|
// Get all items in Origin table
|
|
const originRows = base.getRows(originTable, originView);
|
|
|
|
// Fill elements with every item, count and quantity
|
|
originRows.forEach(row => {
|
|
|
|
const clientName = row[originClientColumnName];
|
|
const quantity = Math.abs(row[originQuantityColumnName]);
|
|
const element = { "count": 0, "quantity": 0 };
|
|
|
|
if (elements[clientName]) {
|
|
element.count = elements[clientName].count;
|
|
element.quantity = elements[clientName].quantity;
|
|
element["count"] += 1;
|
|
element["quantity"] += quantity;
|
|
elements[clientName]["count"] = element.count;
|
|
elements[clientName]["quantity"] = element.quantity;
|
|
} else {
|
|
|
|
elements[clientName] = {};
|
|
elements[clientName].count = 1
|
|
elements[clientName].quantity = quantity;
|
|
}
|
|
});
|
|
|
|
// Create array of arrays from object 'elements'
|
|
clientsList = Object.entries(elements);
|
|
|
|
// If Table is not empty, delete all rows
|
|
const resultRows = base.getRows(resultTable, resultView);
|
|
if (resultRows.length > 0) {
|
|
const row_ids = resultRows.map(row => row._id);
|
|
row_ids.map(row_id => base.deleteRowById(resultTable, row_id));
|
|
}
|
|
|
|
// Add new rows
|
|
clientsList.forEach((client) => {
|
|
|
|
clientData = {
|
|
[resultClientColumnName]: client[0],
|
|
[resultCountColumnName]: client[1].count,
|
|
[resultQuantityColumnName]: client[1].quantity
|
|
};
|
|
base.addRow(resultTable, clientData);
|
|
|
|
});
|