Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Data CSV export ve Send email Script #143

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
Open
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,18 @@ fields: {
Opsiyonel her türlü yardım isteme ve yardımEt kısmına eklenecek özellikler için
fields alanını kullanın isteidğiniz gibi json objesi post edebilirsiniz

## Local Email Saglayici Ayari

Export E-Mail ozelligi icin email saglayicinin API key degerini .env dosyasina girmeniz gerekmektedir.

Ayrica email atilmasi istediginiz hesaplari (coklu ise virgul ile ayirarak) asagidaki gibi tanimlayiniz.

e.g.
```.env
EMAIL_PROVIDER_API_KEY="EXAMPLEAPIKEY"
EXPORT_EMAILS="email@example.com"
```

## Cache i temizleme

/cache/flushall
Expand Down Expand Up @@ -209,6 +221,11 @@ istenen yardımların altında form var süreci takip etmek için yardimKaydi ol
- exportYardimEtCsv.js
`node scripts/exportYardimEtCsv.js`
YardimEt datasını csv export eder
- exportVeMail.js
`node scripts/exportVeMail.js modelIsmi islem=islemAdi (dosyaKonumu)`
Modelleri CSV olarak export etmek ve/veya CSV exportlari static email listelerine gondermek icin kullanılır.
modelIsmi e.g. YardimEt
islemAdi mail, export veya print olabilir. export durumunda yazilmasi istenilen local dosya konumu verilmelidir


## Supply chain security
Expand Down
2 changes: 2 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ module.exports = {
mongoUrl: process.env.MONGOURL || "",
redisUrl: process.env.REDIS_URL || "",
NODE_ENV: process.env.NODE_ENV || "development",
exportEmails: process.env.EXPORT_EMAILS || "istenilenstaticemail@mail.com",
emailProviderAPIKey: process.env.EMAIL_PROVIDER_API_KEY || "",
};
71 changes: 71 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"@fastify/redis": "^6.1.0",
"@fastify/swagger": "^8.3.1",
"@fastify/swagger-ui": "^1.3.0",
"@sendgrid/mail": "^7.7.0",
"@lavamoat/allow-scripts": "^2.3.0",
"@lavamoat/preinstall-always-fail": "^1.0.0",
"abstract-cache-redis": "^2.0.0",
Expand Down
213 changes: 213 additions & 0 deletions scripts/exportVeMail.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
const Yardim = require("../models/yardimModel");
const YardimEt = require("../models/yardimEtModel");
const YardimKaydi = require("../models/yardimKaydiModel");
const Iletisim = require("../models/iletisimModel");
const config = require("../config");
const fs = require("fs");
const sgMail = require("@sendgrid/mail");
const mongoose = require('mongoose');
let emailProviderSetup = false;

if (config.emailProviderAPIKey && config.emailProviderAPIKey !== "") {
emailProviderSetup = true;
sgMail.setApiKey(config.emailProviderAPIKey);
}

async function main() {
const args = process.argv;

if (args.length < 4) {
console.log("Kullanim sekli:\n");
console.log("node scripts/exportVeMail.js modelIsmi islem=islemAdi (dosyaKonumu)");
return;
}

let veriTipi = args[2];
let islem = args[3].split("=")[1];
const mailler = config.exportEmails;

await mongoose.connect(config.mongoUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
});

switch (islem) {
case "mail":
let data = await exportData(veriTipi);
await sendEmail(mailler, veriTipi, data);

break;
case "export":
let dosyaIsmi = args[4];
if (!dosyaIsmi) {
console.error("Export islemi icin lutfen bir dosya ismi belirtin");
break;
}

const writeStream = fs.createWriteStream(dosyaIsmi);
await exportData(veriTipi, writeStream);
break;
case "print":
let dataToPrint = await exportData(veriTipi);

console.log("Export edilmis CSV formatinda data: \n");
console.log(dataToPrint);
break;
default:
console.error("Tanimlanmayan islem tipi girdiniz.");
}

mongoose.connection.close();
}

main();

function sendEmail(to, veriTipi, data) {
if (!data || data.length === 0) {
console.error("Email atilacak data bos.");
return;
}
let multipleEmail = to.split(",");
if (multipleEmail.length > 0) {
to = multipleEmail;
}

// Simdilik SendGrid free trier kullanabiliriz, ardindan istenilen saglayiciya gecilebilir
const msg = {
to: to,
from: 'depremiotest@gmail.com',
subject: `deprem.io ${veriTipi} Export`,
html: '<strong>deprem.io ciktilari ektedir.</strong>',
attachments: [
{
content: Buffer.from(data).toString("base64"),
filename: `${veriTipi} export ${Date.now()}.csv`,
type: "text/csv",
disposition: "attachment",
content_id: "depremio_csv"
}
]
}

return sgMail
.send(msg)
.then((response) => {
console.log(`Email saglayici durum kodu: ${response[0].statusCode}`);
console.log(`Email saglayici cevap headerlari: ${response[0].headers}`);
})
.catch((error) => {
console.error(error)
});
}

async function exportData(veriTipi, io) {
let select;
let queryDoc;

if (veriTipi === "YardimEt") {
select = "yardimTipi adSoyad telefon sehir hedefSehir aciklama fields createdAt updatedAt";
queryDoc = YardimEt;
} else if (veriTipi === "Yardim") {
select = "yardimTipi adSoyad telefon email adres adresTarifi acilDurum kisiSayisi yardimDurumu fizikiDurum " +
"googleMapLink tweetLink fields createdAt updatedAt";
queryDoc = Yardim;
} else if (veriTipi === "YardimKaydi") {
select = "yardimTipi adSoyad telefon sonDurum adres email aciklama createdAt updatedAt";
queryDoc = YardimKaydi;
} else if (veriTipi === "Iletisim") {
select = "adSoyad email telefon mesaj createdAt updatedAt";
queryDoc = Iletisim;
} else {
return "";
}

let data = await queryDoc.find({})
.select(select)
.then(data => {
return data;
})
.catch((err) => {
console.error(err);
mongoose.connection.close();
});

data = processData(data, io);

if (io) {
io.end();
}
return data;
}

const header = (obj) => {
if (!obj) return "";
let keys = [];

for (let key of Object.keys(obj)) {
if (typeof (obj[key]) === "object") {
let headerName = header(obj[key]);
if (headerName && headerName.trim() !== "") {
keys.push(headerName);
}
} else {
if (key && key.trim() !== "") {
keys.push(key);
}
}
}

return keys.length > 0 ? keys.join(", ") : "";
};

const row = (obj) => {
if (!obj) return "";
let values = [];

for (let key of Object.keys(obj)) {
if (typeof (obj[key]) === "object") {
let value = row(obj[key]);
if (value) {
values.push(value);
}
} else {
let value = obj[key].replaceAll(",", " "); // separator keyword
if (value) {
values.push(value);
}
}
}

return values.length > 0 ? values.join(", ") : "";
};

const processData = (data, io) => {
if (!data || data.length === 0) {
return "";
}

let csvExportString = "";
let headerString = header(data[0]._doc) + "\n";
csvExportString += headerString;

if (io) {
io.write(headerString, err => {
if (err) {
console.error(err);
}
});
}

data.forEach(dataItem => {
let rowString = row(dataItem._doc) + "\n";
if (io) {
io.write(rowString, err => {
if (err) {
console.error(err);
}
});
}
csvExportString += rowString;
});

return csvExportString;
}