1
0
forked from apxtri/apxtri

modif for docapi

This commit is contained in:
philc 2024-07-11 13:29:54 +02:00
parent 27ce76e53f
commit 3ec0105455
2 changed files with 212 additions and 105 deletions

View File

@ -30,27 +30,32 @@ Notifications.get = (alias, tribeId) => {
/** /**
* Get statistic of registering email phone * Get statistic of registering email phone
*/ */
Notifications.statmaillist=(tribe)=>{ Notifications.statmaillist = (tribe) => {
const statinfo={} const statinfo = {};
let csv="email/phone;name;srckey\n" let csv = "email/phone;name;srckey\n";
const src=`../../${tribe}/objects/maillinglists/*.json` const src = `../../${tribe}/objects/maillinglists/*.json`;
console.log(path.resolve(src)) console.log(path.resolve(src));
glob.sync(src).forEach(f=>{ glob.sync(src).forEach((f) => {
const name=path.basename(f,".json"); const name = path.basename(f, ".json");
const mlst=fs.readJSONSync(f) const mlst = fs.readJSONSync(f);
Object.keys(mlst).forEach(c=>{ Object.keys(mlst).forEach((c) => {
csv+=`"${c}";"${name}";"${mlst[c].srckeys.join('-')}"\n` csv += `"${c}";"${name}";"${mlst[c].srckeys.join("-")}"\n`;
mlst[c].srckeys.forEach(s=>{ mlst[c].srckeys.forEach((s) => {
if (!statinfo[s]) statinfo[s]={} if (!statinfo[s]) statinfo[s] = {};
if (!statinfo[s][name]) statinfo[s][name]=0 if (!statinfo[s][name]) statinfo[s][name] = 0;
statinfo[s][name]++ statinfo[s][name]++;
}) });
}) });
}) });
// fichier csv stocker en local en attendant d'avoir un back pour stocker la reponse dans data.csv // fichier csv stocker en local en attendant d'avoir un back pour stocker la reponse dans data.csv
fs.outputFileSync(`../../${tribe}/mailinglst.csv`,csv,"utf-8"); fs.outputFileSync(`../../${tribe}/mailinglst.csv`, csv, "utf-8");
return {status:200,ref:"Notifications",msg:"statistics",data:statinfo} return {
} status: 200,
ref: "Notifications",
msg: "statistics",
data: statinfo,
};
};
/** /**
* Register an typekey(email) or (phone) key into mailinglist for a tribe * Register an typekey(email) or (phone) key into mailinglist for a tribe
@ -58,19 +63,26 @@ Notifications.statmaillist=(tribe)=>{
*/ */
Notifications.registertolist = (key, typekey, tribe, mlist, srckey, uuid) => { Notifications.registertolist = (key, typekey, tribe, mlist, srckey, uuid) => {
key = key.toLowerCase(); key = key.toLowerCase();
typekey= (typekey=="telephone")? "telephonefr":typekey; typekey = typekey == "telephone" ? "telephonefr" : typekey;
if (!Checkjson.testformat(key, typekey)) if (!Checkjson.testformat(key, typekey))
return { return {
status: 400, status: 400,
ref: "Notifications", ref: "Notifications",
msg: "formaterror", msg: "formaterror",
data: { fielderr: typekey, format: typekey } data: { fielderr: typekey, format: typekey },
}; };
const destin = `../../${tribe}/objects/maillinglists/${typekey}_${mlist}.json`; const destin = `../../${tribe}/objects/maillinglists/${typekey}_${mlist}.json`;
if (!fs.existsSync(destin)){ if (!fs.existsSync(destin)) {
console.log(`######## Attention tentative d'ecriture non autorisé,le fichier n'existe pas ${destin} créer le à la main vide {}`) console.log(
return {status:406,ref:"Notifications",msg:"destinnotallow",data:{destin}} `######## Attention tentative d'ecriture non autorisé,le fichier n'existe pas ${destin} créer le à la main vide {}`
);
return {
status: 406,
ref: "Notifications",
msg: "destinnotallow",
data: { destin },
};
} }
const filestorage = fs.existsSync(destin) ? fs.readJsonSync(destin) : {}; const filestorage = fs.existsSync(destin) ? fs.readJsonSync(destin) : {};
@ -81,28 +93,30 @@ Notifications.registertolist = (key, typekey, tribe, mlist, srckey, uuid) => {
filestorage[key].srckeys.push(srckey); filestorage[key].srckeys.push(srckey);
if (!filestorage[key].uuids.includes(uuid)) if (!filestorage[key].uuids.includes(uuid))
filestorage[key].uuids.push(uuid); filestorage[key].uuids.push(uuid);
}else{ } else {
filestorage[key]={} filestorage[key] = {};
filestorage[key].dt_create=dayjs().toISOString(); filestorage[key].dt_create = dayjs().toISOString();
filestorage[key].srckeys=[srckey]; filestorage[key].srckeys = [srckey];
filestorage[key].uuids=[uuid] filestorage[key].uuids = [uuid];
} }
fs.outputJSONSync(destin, filestorage); fs.outputJSONSync(destin, filestorage);
return {status:200,ref:"Notifications",msg:"registersuccess",data:{key, typekey, tribe, mlist, srckey, uuid}} return {
} status: 200,
ref: "Notifications",
msg: "registersuccess",
data: { key, typekey, tribe, mlist, srckey, uuid },
};
};
/** /**
* Unsubscribe an eamil or phone from a mailinglist for a tribe * Unsubscribe an eamil or phone from a mailinglist for a tribe
*/ */
Notifications.unregisterfromlist = (key, typekey, tribe,mlist) => { Notifications.unregisterfromlist = (key, typekey, tribe, mlist) => {
key = key.toLowerCase(); key = key.toLowerCase();
};
}
/** /**
* Message to send to an alias from an anonymous or not * Message to send to an alias from an anonymous or not
*/ */
Notifications.sendcontact = (body, header) => { Notifications.sendcontact = (body, header) => {};
}
Notifications.sendsms = async (data, tribeId) => { Notifications.sendsms = async (data, tribeId) => {
/** /**
* Never use need wallet in mailjet to test * Never use need wallet in mailjet to test
@ -138,11 +152,7 @@ Notifications.sendsms = async (data, tribeId) => {
}; };
} }
let confsms = conf.sms; let confsms = conf.sms;
if ( if (fs.existsSync(`../../itm/${req.session.header.xtribe}.json`)) {
fs.existsSync(
`../../itm/${req.session.header.xtribe}.json`
)
) {
const conftrib = fs.readJSONSync( const conftrib = fs.readJSONSync(
`../../itm/${req.session.header.xtribe}.json` `../../itm/${req.session.header.xtribe}.json`
); );
@ -195,6 +205,49 @@ Notifications.sendsms = async (data, tribeId) => {
*/ */
}; };
Notifications.manageemail = (data, template, tribe) => {
/**
* Manage email publipostage
* data must contain emailsto
* data optionaly can contain Cc,Bcc as array of emails and attachments as array of filename (into the server)
* Await the 1st email
*/
if (!data.emailsto || data.emailsto.length == 0) {
return {
status: 406,
ref: "Notifications",
msg: "emailsmissing",
data: data,
};
}
if (typeof data.emailsto === "string") data.emailsto = [data.emailsto];
const tplemail = require(path.resolve(template));
let sendit;
data.emailsto.forEach(async (e, i) => {
if (Checkjson.testformat(e, "email")) {
const dat = {};
dat.to = e;
dat.subject = Mustache.render(tplemail.subject, data);
dat.html = Mustache.render(tplemail.subject, data);
dat.text = Mustache.render(tplemail.text, data);
dat.Cc = data.Cc ? tplemail.Cc.push(data.Cc) : tplemail.Cc;
dat.Bcc = data.Bcc ? tplemail.Bcc.push(data.Bcc) : tplemail.Bcc;
dat.attachments = tplemail.attachments.push(data.attachments);
const sendit = Notifications.sendmail(data, tribe);
if (i == 0) {
sendit = await Notifications.sendmail(data, tribe);
if (sendit.status != 200) return sendit;
} else {
Notifications.sendmail(data, tribe);
}
} else {
// not a well formated email
}
});
return sendit;
};
Notifications.sendmail = async (data, tribe) => { Notifications.sendmail = async (data, tribe) => {
/** /**
* See https://nodemailer.com/message/ for available fields to add * See https://nodemailer.com/message/ for available fields to add
@ -264,8 +317,9 @@ Notifications.sendmail = async (data, tribe) => {
let missingfile = []; let missingfile = [];
data.filelist.forEach((fo) => { data.filelist.forEach((fo) => {
if (fs.existsSync(fo.pathfile)) { if (fs.existsSync(fo.pathfile)) {
} else {
} else { missingfile.push(fo.pathfile); } missingfile.push(fo.pathfile);
}
}); });
if (missingfile.lenght > 0) if (missingfile.lenght > 0)
return { return {

View File

@ -8,7 +8,6 @@ const isAuthenticated = require("../middlewares/isAuthenticated");
const router = express.Router(); const router = express.Router();
/** /**
* wait Sagar feedback for language and label description * wait Sagar feedback for language and label description
* @ api {post} /api/notifications/backend - Notification Backend post * @ api {post} /api/notifications/backend - Notification Backend post
@ -21,12 +20,10 @@ const router = express.Router();
* @apiBody {string} msg a key word existing in referentiual * @apiBody {string} msg a key word existing in referentiual
* */ * */
router.post("/backend", (req, res) => { router.post("/backend", (req, res) => {});
})
/** /**
* @api {get} adminapi/notifications/:alias/:tribeId * @api {get} adminapi/notifications/messages/:alias/:tribeId -Get message list for alias in tribe
* @apiName notiflist * @apiName notiflist
* @apiDescription Get list of notifications for an alias and a tribe * @apiDescription Get list of notifications for an alias and a tribe
* @apiGroup Notifications * @apiGroup Notifications
@ -39,11 +36,49 @@ router.post("/backend", (req, res) => {
* {status:200,ref:"Notification",msg:"Messagelist",data:{notif:[{tribeId,msg:{from(email or uuid or alias):[{dt,msg}]}}]} * {status:200,ref:"Notification",msg:"Messagelist",data:{notif:[{tribeId,msg:{from(email or uuid or alias):[{dt,msg}]}}]}
* bouture * bouture
**/ **/
router.get("/:alias/:tribeId", (req, res) => { router.get("/messages/:alias/:tribeId", (req, res) => {
const getnot = Notification.get(req.params.alias, req.params.tribeId); const getnot = Notification.get(req.params.alias, req.params.tribeId);
res.status(getalias.status).send(getalias); res.status(getalias.status).send(getalias);
}); });
/**
* @api {POST} adminapi/notifications/sendmail/:tribe/:template -Send personnalize emails
* @apiName Sendmail
* @apiDescription Send personnalize email with data from template store in ../../{tribe}/template/{template}.json
* @apiGroup Notifications
*
* @apiParam {string} template
* @apiParam {string} tribe
* @apiBody {array} emails to send (array of valid email)
* @apiBody {object} Data to personnalize template
*
* @apiSuccess {object} notif content
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {status:200,ref:"Notification",msg:"Messagelist",data:{notif:[{tribeId,msg:{from(email or uuid or alias):[{dt,msg}]}}]}
* bouture
*/
router.post(
"/sendmail/:tribe/:template/:await",
checkHeaders,
isAuthenticated,
(req, res) => {
const pathtpl = `../../${req.params.tribe}/${req.params.template}.js`;
if (fs.existsSync(pathtpl)) {
const sendemail = Notification.manageemail(req.body, pathtpl,req.params.tribe);
res.status(sendemail.status).send(sendemail);
} else {
res
.status(404)
.send({
status: 404,
ref: "Notification",
msg: "templatenotfound",
data: { pathtpl },
});
}
}
);
/** /**
* @api {POST} adminapi/notifications/registeranonymous/:tribe/:mlist/:typekey/:data -Register email||phone to mlist * @api {POST} adminapi/notifications/registeranonymous/:tribe/:mlist/:typekey/:data -Register email||phone to mlist
@ -61,24 +96,34 @@ router.get("/:alias/:tribeId", (req, res) => {
* {"status":200, "ref":"Notifications", "msg":"registersuccess", "data":{data, typekey, tribe, mlist, srckey, uuid}}} * {"status":200, "ref":"Notifications", "msg":"registersuccess", "data":{data, typekey, tribe, mlist, srckey, uuid}}}
* *
*/ */
router.post("/registeranonymous",checkHeaders,(req,res)=>{ router.post("/registeranonymous", checkHeaders, (req, res) => {
//console.log("list registration ",req.body) //console.log("list registration ",req.body)
if (!req.body.typekey || !['email','telephone'].includes(req.body.typekey) ){ if (!req.body.typekey || !["email", "telephone"].includes(req.body.typekey)) {
return res.status(406).json({status:406,ref:"Notifications",msg:"typekeyunknown",data:{typekey:req.body.typekey}}) return res
.status(406)
.json({
status: 406,
ref: "Notifications",
msg: "typekeyunknown",
data: { typekey: req.body.typekey },
});
} }
const key= (req.body.contactpoint)?req.body.contactpoint:req.body[req.body.typekey]; const key = req.body.contactpoint
result= Notifications.registertolist( ? req.body.contactpoint
key, : req.body[req.body.typekey];
req.body.typekey, result = Notifications.registertolist(
req.body.tribe, key,
req.body.mlist, req.body.typekey,
req.body.srckey, req.body.tribe,
req.session.header.xuuid); req.body.mlist,
req.body.srckey,
req.session.header.xuuid
);
res.status(result.status).json(result) res.status(result.status).json(result);
}) });
/** /**
* @api {GET} adminapi/notifications/unregister/:tribe/:mlist/:typekey/:data/:validation -Unregister email o r phone from a mlist or all mlist * @api {GET} adminapi/notifications/unregister/:tribe/:mlist/:typekey/:data/:validation -Unregister email or phone from a mlist or all mlist
* @apiName unregister * @apiName unregister
* @apiGroup Notifications * @apiGroup Notifications
* @apiDescription Register an email into a mailinglist mlist * @apiDescription Register an email into a mailinglist mlist
@ -95,16 +140,21 @@ router.post("/registeranonymous",checkHeaders,(req,res)=>{
* *
*/ */
router.get("/unregister/:tribe/:mlist/:typekey/:srckey/:data/:validation", checkHeaders, (req, res) => { router.get(
Notifications.registertolist = (typekey, tribe, mlist, srckey, uuid) "/unregister/:tribe/:mlist/:typekey/:srckey/:data/:validation",
result= Notifications.registertolist( checkHeaders,
req.params.typekey, (req, res) => {
req.params.tribe, Notifications.registertolist = (typekey, tribe, mlist, srckey, uuid);
req.params.mlist, result = Notifications.registertolist(
req.params.srckey, req.params.typekey,
req.session.header.xuuid); req.params.tribe,
res.status(result.status).json(result) req.params.mlist,
}) req.params.srckey,
req.session.header.xuuid
);
res.status(result.status).json(result);
}
);
/** /**
* @api {GET} adminapi/notifications/stat/maillinglst/:tribe --Statistic maillinglst * @api {GET} adminapi/notifications/stat/maillinglst/:tribe --Statistic maillinglst
@ -140,13 +190,11 @@ router.get("/unregister/:tribe/:mlist/:typekey/:srckey/:data/:validation", check
* *
*/ */
router.get("/stat/maillinglst/:tribe", checkHeaders, async (req, res) => { router.get("/stat/maillinglst/:tribe", checkHeaders, async (req, res) => {
console.log('passe là'); console.log("passe là");
const resstat=Notifications.statmaillist(req.params.tribe) const resstat = Notifications.statmaillist(req.params.tribe);
res.status(resstat.status).json(resstat); res.status(resstat.status).json(resstat);
}); });
/** /**
* @api {POST} adminapi/notifications/contactanonymous/:tribe -Contact anonymous * @api {POST} adminapi/notifications/contactanonymous/:tribe -Contact anonymous
* @apiName contactanonymous * @apiName contactanonymous
@ -173,13 +221,18 @@ router.post("/contactanonymous", checkHeaders, async (req, res) => {
/** /**
* Same as /copntactanonymous but for authenticated user => data are updated in persons/itm/alias.json * Same as /copntactanonymous but for authenticated user => data are updated in persons/itm/alias.json
*/ */
router.post("/contact/:tribe/:alias", checkHeaders, isAuthenticated, (req, res) => { router.post(
const done = Actions[req.body.order] "/contact/:tribe/:alias",
? Actions[req.body.order](req.body, req.session.header) checkHeaders,
: { status: 406, ref: "Actions", msg: "bodyerror", data: req.body }; isAuthenticated,
console.log(req.body); (req, res) => {
res.status(done.status).json(done); const done = Actions[req.body.order]
}); ? Actions[req.body.order](req.body, req.session.header)
: { status: 406, ref: "Actions", msg: "bodyerror", data: req.body };
console.log(req.body);
res.status(done.status).json(done);
}
);
router.get("/contact", checkHeaders, isAuthenticated, (req, res) => { router.get("/contact", checkHeaders, isAuthenticated, (req, res) => {
res.status(200).json({ data: {} }); res.status(200).json({ data: {} });