How to use messageFormatter method in Jest

Best JavaScript code snippet using jest

TimerService.js

Source:TimerService.js Github

copy

Full Screen

1var mongoose = require('mongoose');2var logger = require('dvp-common/LogHandler/CommonLogHandler.js').logger;3var TimeEntry = require('dvp-mongomodels/model/TimeEntry').TimeEntry;4var Ticket = require('dvp-mongomodels/model/Ticket').Ticket;5var TicketEvent = require('dvp-mongomodels/model/Ticket').TicketEvent;6var User = require('dvp-mongomodels/model/User');7var messageFormatter = require('dvp-common/CommonMessageGenerator/ClientMessageJsonFormatter.js');8var moment = require('moment');9var unique = require("array-unique");10var util = require('util');11function CreateTimer(req, res){12 logger.debug("DVP-LiteTicket.CreateTimer Internal method ");13 var jsonString;14 var tenant = parseInt(req.user.tenant);15 var company = parseInt(req.user.company);16 Ticket.findOne({_id: req.body.ticket, company: company, tenant: tenant}, function (err, ticket) {17 if (err) {18 jsonString = messageFormatter.FormatMessage(err, "Fail To Find Ticket", false, undefined);19 res.end(jsonString);20 }21 else {22 if (ticket) {23 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {24 if (err) {25 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);26 res.end(jsonString);27 }28 else {29 if (user) {30 TimeEntry.findOne({31 user: user.id,32 running: true,33 company: company,34 //time_events: [{state:'start', time: Date.now()}],35 //last_event:'start',36 tenant: tenant37 }, function (err, forms) {38 if ((err || !forms)&& req.body) {39 var timeentry = TimeEntry({40 user: user.id,41 ticket: req.body.ticket,42 startTime: Date.now(),43 running: true,44 time: 0,45 last_event_date: Date.now(),46 company: parseInt(req.user.company),47 tenant: parseInt(req.user.tenant)48 });49 timeentry.save(function (err, form) {50 if (err) {51 jsonString = messageFormatter.FormatMessage(err, "Time entry saved failed", false, undefined);52 res.end(jsonString);53 } else {54 jsonString = messageFormatter.FormatMessage(undefined, "Time entry saved successfully", true, timeentry);55 //res.end(jsonString);56 /////////////////////////////////////////////////////////////////////////////////57 var tEvent = TicketEvent({58 "author": req.user.iss,59 "create_at": Date.now(),60 type: 'tracker',61 body: {62 "message": req.user.iss + " created time entry",63 "time": new Date()64 }65 });66 ticket.events.push(tEvent);67 ////////////////////////////////////////////////ticket matrix/////////////////////////////////////////68 if(ticket.ticket_matrix) {69 ticket.ticket_matrix.last_updated = new Date();70 if(!ticket.ticket_matrix.worked_time)71 ticket.ticket_matrix.worked_time =0;72 }73 if(ticket.collaborators && util.isArray(ticket.collaborators)){74 if(ticket.collaborators.indexOf(user._id) == -1) {75 ticket.collaborators.push(user._id);76 }77 }else{78 ticket.collaborators = [user._id];79 }80 ticket.save(function (err, ticket_save) {81 if (err) {82 jsonString = messageFormatter.FormatMessage(err, "Fail Save Ticket", false, undefined);83 }84 else {85 if (ticket_save) {86 jsonString = messageFormatter.FormatMessage(undefined, "Ticket Saved Successfully", true, timeentry);87 }88 else {89 jsonString = messageFormatter.FormatMessage(undefined, "Invalid Ticket ID.", false, undefined);90 }91 }92 res.end(jsonString);93 });94 ///////////////////////////////////////////////////////////////////////////////////////////////////////95 }96 });97 } else {98 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Successful", true, forms);99 res.end(jsonString);100 }101 });102 }else{103 jsonString = messageFormatter.FormatMessage(undefined, "User Not found", false, undefined);104 res.end(jsonString);105 }106 }107 });108 }109 else {110 jsonString = messageFormatter.FormatMessage(undefined, "Invalid Ticket ID.", false, undefined);111 res.end(jsonString);112 }113 }114 });115};116function GetTimes(req, res){117 logger.debug("DVP-LiteTicket.GetTimes Internal method ");118 var company = parseInt(req.user.company);119 var tenant = parseInt(req.user.tenant);120 var jsonString;121 TimeEntry.find({company: company, tenant: tenant}, function(err, forms) {122 if (err) {123 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Failed", false, undefined);124 }else {125 if (forms) {126 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Successful", true, forms);127 }else{128 jsonString = messageFormatter.FormatMessage(undefined, "No Time entries Found", false, undefined);129 }130 }131 res.end(jsonString);132 });133};134function GetTimesForUser(req, res){135 logger.debug("DVP-LiteTicket.GetTimesForUser Internal method ");136 var company = parseInt(req.user.company);137 var tenant = parseInt(req.user.tenant);138 var jsonString;139 if(req.query && req.query['from']&& req.query['to']) {140 var from = req.query['from'];141 var to = req.query['to'];142 try {143 from = new Date(from);144 to = new Date(to);145 } catch (ex) {146 jsonString = messageFormatter.FormatMessage(ex, "From and To dates are require", false, undefined);147 res.end(jsonString);148 return;149 }150 if (from > to) {151 jsonString = messageFormatter.FormatMessage(undefined, "From should less than To", false, undefined);152 res.end(jsonString);153 return;154 }155 var tempQuery = {company: company, tenant: tenant};156 tempQuery['startTime'] = {$gte: from, $lte: to};157 tempQuery.user= req.params.uid;158 tempQuery.company= company;159 tempQuery.tenant= tenant;160 TimeEntry.find(tempQuery).populate('user' , '-password').populate('ticket').exec(function (err, forms) {161 if (err) {162 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Failed", false, undefined);163 } else {164 if (forms) {165 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Successful", true, forms);166 } else {167 jsonString = messageFormatter.FormatMessage(undefined, "No Time entries Found", false, undefined);168 }169 }170 res.end(jsonString);171 });172 }else{173 jsonString = messageFormatter.FormatMessage(undefined, "From and To dates are require", false, undefined);174 res.end(jsonString);175 }176};177function GetTimesForTicket(req, res){178 logger.debug("DVP-LiteTicket.GetTimesForTicket Internal method ");179 var company = parseInt(req.user.company);180 var tenant = parseInt(req.user.tenant);181 var jsonString;182 TimeEntry.find({ticket: req.params.tid, company: company, tenant: tenant}, function(err, forms) {183 if (err) {184 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Failed", false, undefined);185 }else {186 if (forms) {187 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Successful", true, forms);188 }else{189 jsonString = messageFormatter.FormatMessage(undefined, "No Time entries Found", false, undefined);190 }191 }192 res.end(jsonString);193 });194};195function GetTimesForTicketByUser(req, res){196 logger.debug("DVP-LiteTicket.GetTimesForTicket Internal method ");197 var company = parseInt(req.user.company);198 var tenant = parseInt(req.user.tenant);199 var jsonString;200 TimeEntry.find({user: req.params.uid,ticket: req.params.tid, company: company, tenant: tenant}, function(err, forms) {201 if (err) {202 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Failed", false, undefined);203 }else {204 if (forms) {205 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Successful", true, forms);206 }else{207 jsonString = messageFormatter.FormatMessage(undefined, "No Time entries Found", false, undefined);208 }209 }210 res.end(jsonString);211 });212};213function GetTime(req, res){214 logger.debug("DVP-LiteTicket.GetTimes Internal method ");215 var company = parseInt(req.user.company);216 var tenant = parseInt(req.user.tenant);217 var jsonString;218 TimeEntry.findOne({id:req.params.is,company: company, tenant: tenant}, function(err, forms) {219 if (err) {220 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Failed", false, undefined);221 }else {222 if (forms) {223 jsonString = messageFormatter.FormatMessage(err, "Get Time entries Successful", true, forms);224 }else{225 jsonString = messageFormatter.FormatMessage(undefined, "No Time entries Found", false, undefined);226 }227 }228 res.end(jsonString);229 });230};231function GetMyTimes(req, res){232 logger.debug("DVP-LiteTicket.GetMyTimeSheet Internal method ");233 var company = parseInt(req.user.company);234 var tenant = parseInt(req.user.tenant);235 var jsonString;236 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {237 if (err) {238 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);239 res.end(jsonString);240 }241 else {242 if (user) {243 TimeEntry.find({user: user.id, company: company, tenant: tenant}, function(err, forms) {244 if (err) {245 jsonString = messageFormatter.FormatMessage(err, "Get my Time entries Failed", false, undefined);246 }else {247 if (forms) {248 jsonString = messageFormatter.FormatMessage(err, "Get my Time entries Successful", true, forms);249 }else{250 jsonString = messageFormatter.FormatMessage(undefined, "No Time entries Found", false, undefined);251 }252 }253 res.end(jsonString);254 });255 }256 else {257 jsonString = messageFormatter.FormatMessage(undefined, "Get User Failed", false, undefined);258 res.end(jsonString);259 }260 }261 });262};263function DeleteMyTimer(req, res) {264 logger.debug("DVP-LiteTicket.DeleteMyTimes Internal method ");265 var company = parseInt(req.user.company);266 var tenant = parseInt(req.user.tenant);267 var jsonString;268 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {269 if (err) {270 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);271 res.end(jsonString);272 }273 else {274 if (user) {275 TimeEntry.findOneAndRemove({276 user: user.id,277 running: true,278 company: company,279 tenant: tenant280 }, function (err, forms) {281 if (err) {282 jsonString = messageFormatter.FormatMessage(err, "Get my Time entries Failed", false, undefined);283 } else {284 if (forms) {285 jsonString = messageFormatter.FormatMessage(err, "Get my Time entries Successful", true, forms);286 } else {287 jsonString = messageFormatter.FormatMessage(undefined, "No Time entries Found", false, undefined);288 }289 }290 res.end(jsonString);291 });292 }293 else {294 jsonString = messageFormatter.FormatMessage(undefined, "Get User Failed", false, undefined);295 res.end(jsonString);296 }297 }298 });299};300function GetMyTimer(req, res) {301 logger.debug("DVP-LiteTicket.GetMyTimer Internal method ");302 var company = parseInt(req.user.company);303 var tenant = parseInt(req.user.tenant);304 var jsonString;305 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {306 if (err) {307 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);308 res.end(jsonString);309 }310 else {311 if (user) {312 TimeEntry.findOne({313 user: user.id,314 running: true,315 company: company,316 tenant: tenant317 }, function (err, forms) {318 if (err) {319 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Failed", false, undefined);320 } else {321 if (forms) {322 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Successful", true, forms);323 } else {324 jsonString = messageFormatter.FormatMessage(undefined, "No Time entry Found", false, undefined);325 }326 }327 res.end(jsonString);328 });329 }330 else {331 jsonString = messageFormatter.FormatMessage(undefined, "Get User Failed", false, undefined);332 res.end(jsonString);333 }334 }335 });336};337function UpdateMyTimerTicket(req, res){338 logger.debug("DVP-LiteTicket.UpdateMyTimerTicket Internal method ");339 var company = parseInt(req.user.company);340 var tenant = parseInt(req.user.tenant);341 var jsonString;342 Ticket.findOne({_id: req.params.tid, company: company, tenant: tenant}, function (err, ticket) {343 if (err) {344 jsonString = messageFormatter.FormatMessage(err, "Fail To Find Ticket", false, undefined);345 res.end(jsonString);346 }347 else {348 if (ticket) {349 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {350 if (err) {351 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);352 res.end(jsonString);353 }354 else {355 if (user) {356 TimeEntry.findOneAndUpdate({_id: req.params.id, user: user.id, running: true, company: company, tenant: tenant}, {ticket: req.params.tid},function(err, forms) {357 if (err) {358 jsonString = messageFormatter.FormatMessage(err, "Update Time entry Failed", false, undefined);359 }else {360 if (forms) {361 jsonString = messageFormatter.FormatMessage(err, "Update Time entry Successful", true, forms);362 }else{363 jsonString = messageFormatter.FormatMessage(undefined, "No Time entry Found", false, undefined);364 }365 }366 res.end(jsonString);367 });368 }else{369 jsonString = messageFormatter.FormatMessage(undefined, "User Not found", false, undefined);370 res.end(jsonString);371 }372 }373 });374 }375 else {376 jsonString = messageFormatter.FormatMessage(undefined, "Invalid Ticket ID.", false, undefined);377 res.end(jsonString);378 }379 }380 });381};382function UpdateMyTimerTime(req, res){383 logger.debug("DVP-LiteTicket.UpdateMyTimerTime Internal method ");384 var company = parseInt(req.user.company);385 var tenant = parseInt(req.user.tenant);386 var jsonString;387 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {388 if (err) {389 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);390 res.end(jsonString);391 }392 else {393 if (user) {394 TimeEntry.findOneAndUpdate({_id: req.params.id, running: true, company: company, tenant: tenant}, {time: req.params.time},function(err, forms) {395 if (err) {396 jsonString = messageFormatter.FormatMessage(err, "Update Time entry Failed", false, undefined);397 }else {398 if (forms) {399 jsonString = messageFormatter.FormatMessage(err, "Update Time entry Successful", true, forms);400 }else{401 jsonString = messageFormatter.FormatMessage(undefined, "No Time entry Found", false, undefined);402 }403 }404 res.end(jsonString);405 });406 }407 else {408 jsonString = messageFormatter.FormatMessage(undefined, "Get User Failed", false, undefined);409 res.end(jsonString);410 }411 }412 });413};414function StartTimer(req, res){415 logger.debug("DVP-LiteTicket.StartTimer Internal method ");416 var company = parseInt(req.user.company);417 var tenant = parseInt(req.user.tenant);418 var jsonString;419 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {420 if (err) {421 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);422 res.end(jsonString);423 }424 else {425 if (user) {426 TimeEntry.findOne({user: user.id, running: true, last_event:'pause', company: company, tenant: tenant}, function(err, timer) {427 if (err) {428 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Failed", false, undefined);429 res.end(jsonString);430 }else {431 if (timer) {432 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Successfull", true, timer);433 var timeevent = {state:'start', time: Date.now()};434 if(req.body && req.body.note){435 timeevent["note"] = req.body.note;436 }437 TimeEntry.findOneAndUpdate(438 {user: user.id, running: true, last_event:'pause', company: company, tenant: tenant},439 {440 last_event_date: Date.now(),441 last_event:'start',442 running: true,443 $addToSet:{time_events:timeevent},444 },function(err, timer) {445 if (err) {446 jsonString = messageFormatter.FormatMessage(err, "Add Time entry Failed", false, timer);447 }else {448 jsonString = messageFormatter.FormatMessage(err, "AddTime entry successfull", true, timer);449 }450 res.end(jsonString);451 });452 }else{453 jsonString = messageFormatter.FormatMessage(undefined, "No Time entry Found", false, undefined);454 res.end(jsonString);455 }456 }457 });458 }459 else {460 jsonString = messageFormatter.FormatMessage(undefined, "Get User Failed", false, undefined);461 res.end(jsonString);462 }463 }464 });465};466function PauseTimer(req, res){467 logger.debug("DVP-LiteTicket.PauseTimer Internal method ");468 var company = parseInt(req.user.company);469 var tenant = parseInt(req.user.tenant);470 var jsonString;471 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {472 if (err) {473 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);474 res.end(jsonString);475 }476 else {477 if (user) {478 TimeEntry.findOne({user: user.id, _id: req.params.id, company: company, tenant: tenant}, function(err, timer) {479 if (err) {480 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Failed", false, undefined);481 res.end(jsonString);482 }else {483 if (timer) {484 if (timer.running && timer.last_event == 'start') {485 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Successfull", true, timer);486 var timeevent = {state: 'pause', time: Date.now()};487 if (req.body && req.body.note) {488 timeevent["note"] = req.body.note;489 }490 var ms = moment(Date.now()).diff(moment(timer.last_event_date));491 var d = moment.duration(ms);492 var time = timer.time + d;493 TimeEntry.findOneAndUpdate(494 {495 user: user.id,496 running: true,497 last_event: 'start',498 company: company,499 tenant: tenant500 },501 {502 last_event_date: Date.now(),503 time: time,504 last_event: 'pause',505 $addToSet: {time_events: timeevent},506 }, function (err, timer) {507 if (err) {508 jsonString = messageFormatter.FormatMessage(err, "Add Time entry Failed", false, timer);509 } else {510 jsonString = messageFormatter.FormatMessage(err, "AddTime entry successfull", true, timer);511 }512 res.end(jsonString);513 });514 } else {515 jsonString = messageFormatter.FormatMessage(undefined, "No Time entry Found", false, undefined);516 res.end(jsonString);517 }518 }else{519 jsonString = messageFormatter.FormatMessage(err, "AddTime entry successfull", true, timer);520 res.end(jsonString);521 }522 }523 });524 }525 else {526 jsonString = messageFormatter.FormatMessage(undefined, "Get User Failed", false, undefined);527 res.end(jsonString);528 }529 }530 });531};532function StopTimer(req, res){533 logger.debug("DVP-LiteTicket.StopTimer Internal method ");534 var company = parseInt(req.user.company);535 var tenant = parseInt(req.user.tenant);536 var jsonString;537 User.findOne({username: req.user.iss, company: company, tenant: tenant}, function (err, user) {538 if (err) {539 jsonString = messageFormatter.FormatMessage(err, "Get User Failed", false, undefined);540 res.end(jsonString);541 }542 else {543 if (user) {544 TimeEntry.findOne({user: user.id, _id:req.params.id, company: company, tenant: tenant}, function(err, timer) {545 if (err) {546 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Failed", false, undefined);547 res.end(jsonString);548 }else {549 if (timer) {550 if (timer.running) {551 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Successful", true, timer);552 var timeevent = {state: 'stop', time: Date.now()};553 if (req.body && req.body.note) {554 timeevent["note"] = req.body.note;555 }556 var time = timer.time;557 if (timer.last_event == 'start') {558 var ms = moment(Date.now()).diff(moment(timer.last_event_date));559 var d = moment.duration(ms);560 time = timer.time + d;561 }562 TimeEntry.findOneAndUpdate(563 {user: user.id, running: true, company: company, tenant: tenant},564 {565 last_event_date: Date.now(),566 time: time,567 last_event: 'stop',568 running: false,569 $addToSet: {time_events: timeevent}570 }, function (err, timer) {571 if (err) {572 jsonString = messageFormatter.FormatMessage(err, "Add Time entry Failed", false, timer);573 res.end(jsonString);574 } else {575 if (timer) {576 jsonString = messageFormatter.FormatMessage(err, "AddTime entry successfully", true, timer);577 Ticket.findOne({578 company: company,579 tenant: tenant,580 _id: timer.ticket581 }, function (err, ticket) {582 if (err) {583 jsonString = messageFormatter.FormatMessage(err, "Fail Find Ticket", false, undefined);584 res.end(jsonString);585 }586 else {587 if (ticket) {588 var tEvent = TicketEvent({589 type: 'tracker',590 "author": req.user.iss,591 "create_at": Date.now(),592 body: {593 "message": req.user.iss + " added time " + time,594 "time": new Date()595 }596 });597 ticket.events.push(tEvent);598 ////////////////////////////////////////////////ticket matrix/////////////////////////////////////////599 if (ticket.ticket_matrix) {600 ticket.ticket_matrix.last_updated = new Date();601 ticket.ticket_matrix.worked_time = time;602 }603 ///////////////////////////////////////////////////////////////////////////////////////////////////////604 ticket.save(function (err, rUser) {605 if (err) {606 jsonString = messageFormatter.FormatMessage(err, "Fail Update Ticket", false, undefined);607 }608 else {609 if (rUser) {610 jsonString = messageFormatter.FormatMessage(undefined, "Ticket Update Successfully", true, timer);611 }612 else {613 jsonString = messageFormatter.FormatMessage(undefined, "Invalid Ticket ID.", false, timer);614 }615 }616 res.end(jsonString);617 });618 }619 else {620 jsonString = messageFormatter.FormatMessage(undefined, "Fail Find Ticket", false, undefined);621 res.end(jsonString);622 }623 }624 });625 } else {626 jsonString = messageFormatter.FormatMessage(undefined, "Add Time entry Failed", false, timer);627 res.end(jsonString);628 }629 ////////////////////////////update ticket////////////////////////////////////////////////////630 }631 });632 } else {633 jsonString = messageFormatter.FormatMessage(undefined, "No Time entry Found", false, undefined);634 res.end(jsonString);635 }636 }else{637 jsonString = messageFormatter.FormatMessage(err, "Get Time entry Successful", true, timer);638 res.end(jsonString);639 }640 }641 });642 }643 else {644 jsonString = messageFormatter.FormatMessage(undefined, "Get User Failed", false, undefined);645 res.end(jsonString);646 }647 }648 });649};650module.exports.DeleteMyTimer = DeleteMyTimer;651module.exports.StartTimer = StartTimer;652module.exports.CreateTimer =CreateTimer;653module.exports.GetTimes = GetTimes;654module.exports.GetTimesForUser = GetTimesForUser;655module.exports.GetTimesForTicket = GetTimesForTicket;656module.exports.GetTimesForTicketByUser = GetTimesForTicketByUser;657module.exports.GetTime = GetTime;658module.exports.GetMyTimer = GetMyTimer;659module.exports.GetMyTimes = GetMyTimes;660module.exports.UpdateMyTimerTicket = UpdateMyTimerTicket;661module.exports.UpdateMyTimerTime = UpdateMyTimerTime;662module.exports.PauseTimer = PauseTimer;...

Full Screen

Full Screen

FormService.js

Source:FormService.js Github

copy

Full Screen

1var mongoose = require('mongoose');2var logger = require('dvp-common/LogHandler/CommonLogHandler.js').logger;3var FormMaster = require('dvp-mongomodels/model/FormMaster').FormMaster;4var FormSubmission = require('dvp-mongomodels/model/FormMaster').FormSubmission;5var FormProfile = require('dvp-mongomodels/model/FormMaster').FormProfile;6var IsolatedTagForm = require('dvp-mongomodels/model/FormMaster').FormIsolatedTag;7var messageFormatter = require('dvp-common/CommonMessageGenerator/ClientMessageJsonFormatter.js');8function CreateForm(req, res) {9 logger.debug("DVP-LiteTicket.CreateForm Internal method ");10 var jsonString;11 var tenant = parseInt(req.user.tenant);12 var company = parseInt(req.user.company);13 if (req.body && req.body.name) {14 var form = FormMaster({15 name: req.body.name,16 company: parseInt(req.user.company),17 tenant: parseInt(req.user.tenant)18 });19 if (req.body.fields) {20 form.fields = req.body.fields;21 }22 form.save(function (err, form) {23 if (err) {24 jsonString = messageFormatter.FormatMessage(err, "Form save failed", false, undefined);25 res.end(jsonString);26 } else {27 jsonString = messageFormatter.FormatMessage(undefined, "Form saved successfully", true, form);28 res.end(jsonString);29 }30 });31 } else {32 jsonString = messageFormatter.FormatMessage(undefined, "Requre fields not found", false, undefined);33 res.end(jsonString);34 }35};36function AddOrUpdateIsolatedTagForm(req, res) {37 logger.debug("DVP-LiteTicket.UpdateForm Internal method ");38 var jsonString;39 var tenant = parseInt(req.user.tenant);40 var company = parseInt(req.user.company);41 if (req.body && req.params.id)42 {43 IsolatedTagForm.findOne({44 isolated_tag: req.body.isolated_tag,45 company: parseInt(company),46 tenant: parseInt(tenant)47 }, function (err1, isolatedTagFrm) {48 if(isolatedTagFrm)49 {50 //update51 isolatedTagFrm.dynamicForm = req.params.id;52 isolatedTagFrm.update(isolatedTagFrm, function(err, updateRes)53 {54 if (err) {55 jsonString = messageFormatter.FormatMessage(err, "Update Isolated Tag Form Failed", false, null);56 res.end(jsonString);57 } else {58 jsonString = messageFormatter.FormatMessage(null, "Update Form successful", true, updateRes);59 res.end(jsonString);60 }61 })62 }63 else64 {65 if(err1)66 {67 jsonString = messageFormatter.FormatMessage(err1, "Get isolated tag form error", false, null);68 res.end(jsonString);69 }70 else71 {72 var isolatedTagForm = IsolatedTagForm({73 isolated_tag: req.body.isolated_tag,74 company: parseInt(company),75 tenant: parseInt(tenant),76 dynamicForm: req.params.id77 });78 isolatedTagForm.save(function (err, form) {79 if (err) {80 jsonString = messageFormatter.FormatMessage(err, "Form save failed", false, undefined);81 res.end(jsonString);82 } else {83 jsonString = messageFormatter.FormatMessage(undefined, "Form saved successfully", true, form);84 res.end(jsonString);85 }86 });87 }88 }89 });90 } else {91 jsonString = messageFormatter.FormatMessage(undefined, "Requred fields not found", false, undefined);92 res.end(jsonString);93 }94};95function GetFormByTag(req, res) {96 logger.debug("DVP-LiteTicket.GetFormByTag Internal method ");97 var company = parseInt(req.user.company);98 var tenant = parseInt(req.user.tenant);99 var jsonString;100 IsolatedTagForm.findOne({isolated_tag: req.params.isolated_tag, company: company, tenant: tenant}).populate('dynamicForm').exec(function (err, form) {101 if (err) {102 jsonString = messageFormatter.FormatMessage(err, "Get Form Failed", false, null);103 } else {104 if (form) {105 var userObj;106 jsonString = messageFormatter.FormatMessage(err, "Get Form Successful", true, form);107 } else {108 jsonString = messageFormatter.FormatMessage(null, "No Form found", true, null);109 }110 }111 res.end(jsonString);112 });113};114function GetFormsByTags(req, res) {115 logger.debug("DVP-LiteTicket.GetFormsByTags Internal method ");116 var company = parseInt(req.user.company);117 var tenant = parseInt(req.user.tenant);118 var tagArr = req.body.isolated_tags;119 var emptyArr = [];120 var jsonString;121 IsolatedTagForm.find({isolated_tag: { $in: tagArr }, company: company, tenant: tenant}).populate('dynamicForm').exec(function (err, forms) {122 if (err) {123 jsonString = messageFormatter.FormatMessage(err, "Get Forms By Tags Failed", false, emptyArr);124 } else {125 if (forms) {126 jsonString = messageFormatter.FormatMessage(err, "Get Forms By Tags Successful", true, forms);127 } else {128 jsonString = messageFormatter.FormatMessage(null, "No Forms for Tags found", true, emptyArr);129 }130 }131 res.end(jsonString);132 });133};134function GetAllFormsByTags(req, res) {135 logger.debug("DVP-LiteTicket.GetFormsByTags Internal method ");136 var company = parseInt(req.user.company);137 var tenant = parseInt(req.user.tenant);138 var emptyArr = [];139 var jsonString;140 IsolatedTagForm.find({company: company, tenant: tenant}).populate('dynamicForm').exec(function (err, forms) {141 if (err) {142 jsonString = messageFormatter.FormatMessage(err, "Get Forms Failed", false, emptyArr);143 } else {144 if (forms) {145 jsonString = messageFormatter.FormatMessage(err, "Get Forms Successful", true, forms);146 } else {147 jsonString = messageFormatter.FormatMessage(null, "No Forms found", true, emptyArr);148 }149 }150 res.end(jsonString);151 });152};153function DeleteIsolatedTagForm(req, res) {154 logger.debug("DVP-LiteTicket.DeleteIsolatedTagForm Internal method ");155 var company = parseInt(req.user.company);156 var tenant = parseInt(req.user.tenant);157 var jsonString;158 IsolatedTagForm.findOneAndRemove({isolated_tag: req.params.isolatedTag, company: company, tenant: tenant}, function (err, delForm) {159 if (err) {160 jsonString = messageFormatter.FormatMessage(err, "Delete Isolated Tag Form failed", false, null);161 } else {162 jsonString = messageFormatter.FormatMessage(undefined, "Delete Isolated Tag Form Success", true, null);163 }164 res.end(jsonString);165 });166};167function GetForms(req, res) {168 logger.debug("DVP-LiteTicket.GetForms Internal method ");169 var company = parseInt(req.user.company);170 var tenant = parseInt(req.user.tenant);171 var jsonString;172 FormMaster.find({company: company, tenant: tenant}, function (err, forms) {173 if (err) {174 jsonString = messageFormatter.FormatMessage(err, "Get Forms Failed", false, undefined);175 } else {176 if (forms) {177 jsonString = messageFormatter.FormatMessage(err, "Get Forms Successful", true, forms);178 } else {179 jsonString = messageFormatter.FormatMessage(undefined, "No Forms Found", false, undefined);180 }181 }182 res.end(jsonString);183 });184};185function GetForm(req, res) {186 logger.debug("DVP-LiteTicket.GetForm Internal method ");187 var company = parseInt(req.user.company);188 var tenant = parseInt(req.user.tenant);189 var jsonString;190 FormMaster.findOne({name: req.params.name, company: company, tenant: tenant}, function (err, form) {191 if (err) {192 jsonString = messageFormatter.FormatMessage(err, "Get Form Failed", false, undefined);193 } else {194 if (form) {195 var userObj;196 jsonString = messageFormatter.FormatMessage(err, "Get Form Successful", true, form);197 } else {198 jsonString = messageFormatter.FormatMessage(undefined, "No Form found", false, undefined);199 }200 }201 res.end(jsonString);202 });203};204function DeleteForm(req, res) {205 logger.debug("DVP-LiteTicket.DeleteForm Internal method ");206 var company = parseInt(req.user.company);207 var tenant = parseInt(req.user.tenant);208 var jsonString;209 FormMaster.findOneAndRemove({name: req.params.name, company: company, tenant: tenant}, function (err, user) {210 if (err) {211 jsonString = messageFormatter.FormatMessage(err, "Delete Form failed", false, undefined);212 } else {213 jsonString = messageFormatter.FormatMessage(undefined, "Delete Form Success", true, undefined);214 }215 res.end(jsonString);216 });217};218function AddDynamicField(req, res) {219 logger.debug("DVP-LiteTicket.AddDynamicField Internal method ");220 var company = parseInt(req.user.company);221 var tenant = parseInt(req.user.tenant);222 var jsonString;223 req.body.updated_at = Date.now();224 FormMaster.findOneAndUpdate({name: req.params.name, company: company, tenant: tenant}, {225 $addToSet: {226 fields: {227 field: req.body.field,228 type: req.body.type,229 description: req.body.description,230 title: req.body.title,231 active: req.body.activw,232 require: req.body.require,233 values: req.body.values234 }235 }236 }, function (err, fields) {237 if (err) {238 jsonString = messageFormatter.FormatMessage(err, "Add Dynamic Fields Failed", false, undefined);239 } else {240 jsonString = messageFormatter.FormatMessage(undefined, "Add Dynamic Fields Successful", true, fields);241 }242 res.end(jsonString);243 });244};245function RemoveDynamicField(req, res) {246 logger.debug("DVP-LiteTicket.RemoveDynamicField Internal method ");247 var company = parseInt(req.user.company);248 var tenant = parseInt(req.user.tenant);249 var jsonString;250 FormMaster.findOneAndUpdate({251 name: req.params.name,252 company: company,253 tenant: tenant254 }, {$pull: {'fields': {'field': req.params.field}}}, function (err, fields) {255 if (err) {256 jsonString = messageFormatter.FormatMessage(err, "Remove Dynamic Fields Failed", false, undefined);257 } else {258 jsonString = messageFormatter.FormatMessage(undefined, "Remove Dynamic Fields successfully", false, fields);259 }260 res.end(jsonString);261 });262};263function UpdateDynamicField(req, res) {264 logger.debug("DVP-LiteTicket.GetForm Internal method ");265 var company = parseInt(req.user.company);266 var tenant = parseInt(req.user.tenant);267 var jsonString;268 FormMaster.update({name: req.params.name, company: company, tenant: tenant, 'fields.field': req.params.field}, {269 $set: {270 "fields.$.field": req.body.field,271 "fields.$.type": req.body.type,272 "fields.$.description": req.body.description,273 "fields.$.title": req.body.title,274 "fields.$.active": req.body.active,275 "fields.$.require": req.body.require,276 "fields.$.values": req.body.values277 }278 }, {upsert: true}, function (err, form) {279 if (err) {280 jsonString = messageFormatter.FormatMessage(err, "Get Form Failed", false, undefined);281 res.end(jsonString);282 } else {283 jsonString = messageFormatter.FormatMessage(undefined, "Update Field successful", true, form);284 res.end(jsonString);285 }286 });287};288function CreateFormSubmission(req, res) {289 logger.debug("DVP-LiteTicket.CreateFormSubmission Internal method ");290 var jsonString;291 var tenant = parseInt(req.user.tenant);292 var company = parseInt(req.user.company);293 if (req.body && req.body.form && req.body.reference) {294 FormMaster.findOne({name: req.body.form, company: company, tenant: tenant}, function (err, formmaster) {295 if (err) {296 jsonString = messageFormatter.FormatMessage(err, "Get Form Failed", false, undefined);297 res.end(jsonString);298 } else {299 if (formmaster) {300 var form = FormSubmission({301 form: formmaster.id,302 reference: req.body.reference,303 company: parseInt(req.user.company),304 tenant: parseInt(req.user.tenant),305 fields: req.body.fields306 });307 form.save(function (err, formsub) {308 if (err) {309 jsonString = messageFormatter.FormatMessage(err, "Form save failed", false, undefined);310 res.end(jsonString);311 } else {312 jsonString = messageFormatter.FormatMessage(undefined, "Form saved successfully", true, formsub);313 res.end(jsonString);314 }315 });316 } else {317 jsonString = messageFormatter.FormatMessage(undefined, "No Form found", false, undefined);318 res.end(jsonString);319 }320 }321 });322 } else {323 jsonString = messageFormatter.FormatMessage(undefined, "Require fields not found", false, undefined);324 res.end(jsonString);325 }326};327function UpdateFormSubmission(req, res) {328 logger.debug("DVP-LiteTicket.UpdateDynamicFieldSubmission Internal method ");329 var company = parseInt(req.user.company);330 var tenant = parseInt(req.user.tenant);331 var jsonString;332 FormSubmission.findOneAndUpdate({333 reference: req.params.reference,334 company: company,335 tenant: tenant},336 {337 fields: req.body.fields338 }, function (err, form) {339 if (err) {340 jsonString = messageFormatter.FormatMessage(err, "Get Form Failed", false, undefined);341 res.end(jsonString);342 } else {343 jsonString = messageFormatter.FormatMessage(undefined, "Update Field successful", true, form);344 res.end(jsonString);345 }346 });347};348function GetFormSubmissions(req, res) {349 logger.debug("DVP-LiteTicket.GetFormSubmissions Internal method ");350 var company = parseInt(req.user.company);351 var tenant = parseInt(req.user.tenant);352 var jsonString;353 FormSubmission.find({company: company, tenant: tenant}).populate('FormMaster').exec(function (err, forms) {354 if (err) {355 jsonString = messageFormatter.FormatMessage(err, "Get Forms Failed", false, undefined);356 } else {357 if (forms) {358 jsonString = messageFormatter.FormatMessage(err, "Get Forms Successful", true, forms);359 } else {360 jsonString = messageFormatter.FormatMessage(undefined, "No Forms Found", false, undefined);361 }362 }363 res.end(jsonString);364 });365};366function GetFormSubmission(req, res) {367 logger.debug("DVP-LiteTicket.GetFormSubmission Internal method ");368 var company = parseInt(req.user.company);369 var tenant = parseInt(req.user.tenant);370 var jsonString;371 FormSubmission.findOne({372 reference: req.params.reference,373 company: company,374 tenant: tenant375 }).populate('form').exec(function (err, form) {376 if (err) {377 jsonString = messageFormatter.FormatMessage(err, "Get Form Failed", false, undefined);378 } else {379 if (form) {380 var userObj;381 jsonString = messageFormatter.FormatMessage(err, "Get Form Successful", true, form);382 } else {383 jsonString = messageFormatter.FormatMessage(undefined, "No Form found", false, undefined);384 }385 }386 res.end(jsonString);387 });388};389function DeleteFormSubmission(req, res) {390 logger.debug("DVP-LiteTicket.DeleteFormSubmission Internal method ");391 var company = parseInt(req.user.company);392 var tenant = parseInt(req.user.tenant);393 var jsonString;394 FormSubmission.findOneAndRemove({395 reference: req.params.reference,396 company: company,397 tenant: tenant398 }, function (err, user) {399 if (err) {400 jsonString = messageFormatter.FormatMessage(err, "Delete Form failed", false, undefined);401 } else {402 jsonString = messageFormatter.FormatMessage(undefined, "Delete Form Success", true, undefined);403 }404 res.end(jsonString);405 });406};407function AddDynamicFieldSubmission(req, res) {408 logger.debug("DVP-LiteTicket.AddDynamicFieldSubmission Internal method ");409 var company = parseInt(req.user.company);410 var tenant = parseInt(req.user.tenant);411 var jsonString;412 req.body.updated_at = Date.now();413 FormSubmission.findOneAndUpdate({reference: req.params.reference, company: company, tenant: tenant}, {414 $addToSet: {415 fields: {416 field: req.body.field,417 value: req.body.value418 }419 }420 }, function (err, fields) {421 if (err) {422 jsonString = messageFormatter.FormatMessage(err, "Add Dynamic Fields Failed", false, undefined);423 } else {424 jsonString = messageFormatter.FormatMessage(undefined, "Add Dynamic Fields Successful", true, fields);425 }426 res.end(jsonString);427 });428};429function RemoveDynamicFieldSubmission(req, res) {430 logger.debug("DVP-LiteTicket.RemoveDynamicFieldSubmission Internal method ");431 var company = parseInt(req.user.company);432 var tenant = parseInt(req.user.tenant);433 var jsonString;434 FormSubmission.findOneAndUpdate({435 reference: req.params.reference,436 company: company,437 tenant: tenant438 }, {$pull: {'fields': {'field': req.params.field}}}, function (err, fields) {439 if (err) {440 jsonString = messageFormatter.FormatMessage(err, "Remove Dynamic Fields Failed", false, undefined);441 } else {442 jsonString = messageFormatter.FormatMessage(undefined, "Remove Dynamic Fields successfully", false, fields);443 }444 res.end(jsonString);445 });446};447function UpdateDynamicFieldSubmission(req, res) {448 logger.debug("DVP-LiteTicket.UpdateDynamicFieldSubmission Internal method ");449 var company = parseInt(req.user.company);450 var tenant = parseInt(req.user.tenant);451 var jsonString;452 FormSubmission.findOneAndUpdate({453 reference: req.params.reference,454 company: company,455 tenant: tenant,456 'fields.field': req.params.field457 }, {458 $set: {459 "fields.$.value": req.body.value460 }461 }, {upsert: true}, function (err, form) {462 if (err) {463 jsonString = messageFormatter.FormatMessage(err, "Get Form Failed", false, undefined);464 res.end(jsonString);465 } else {466 jsonString = messageFormatter.FormatMessage(undefined, "Update Field successful", true, form);467 res.end(jsonString);468 }469 });470};471function CreateFormProfile(req, res) {472 logger.debug("DVP-LiteTicket.CreateForm Internal method ");473 var jsonString;474 var tenant = parseInt(req.user.tenant);475 var company = parseInt(req.user.company);476 var form = FormProfile({477 company: parseInt(req.user.company),478 tenant: parseInt(req.user.tenant),479 ticket_form: req.body.ticket_form,480 profile_form: req.body.profile_form481 });482 form.save(function (err, form) {483 if (err) {484 jsonString = messageFormatter.FormatMessage(err, "Form Profile save failed", false, undefined);485 res.end(jsonString);486 } else {487 jsonString = messageFormatter.FormatMessage(undefined, "Form Profile saved successfully", true, form);488 res.end(jsonString);489 }490 });491}492function GetFormProfile(req, res){493 logger.debug("DVP-LiteTicket.GetFormProfile Internal method ");494 var jsonString;495 var tenant = parseInt(req.user.tenant);496 var company = parseInt(req.user.company);497 FormProfile.findOne({company: company, tenant: tenant}).populate("ticket_form").populate("profile_form").exec(498 function(err, forms) {499 if (err) {500 jsonString = messageFormatter.FormatMessage(err, "Get Form Profile Failed", false, undefined);501 }else {502 if (forms) {503 jsonString = messageFormatter.FormatMessage(err, "Get Form Profile Successful", true, forms);504 }else{505 jsonString = messageFormatter.FormatMessage(undefined, "No Form Profile Found", false, undefined);506 }507 }508 res.end(jsonString);509 });510}511function UpdateFormProfile(req, res){512 logger.debug("DVP-LiteTicket.CreateForm Internal method ");513 var jsonString;514 var tenant = parseInt(req.user.tenant);515 var company = parseInt(req.user.company);516 var tempTicketForm = req.body.ticket_form;517 var tempProfileForm = req.body.profile_form;518 if(!tempProfileForm)519 {520 tempProfileForm = null;521 }522 if(!tempTicketForm)523 {524 tempTicketForm = null;525 }526 FormProfile.findOneAndUpdate({company: company, tenant: tenant}, {527 ticket_form: tempTicketForm,528 profile_form: tempProfileForm},529 function(err, forms) {530 if (err) {531 jsonString = messageFormatter.FormatMessage(err, "Form Profile Failed", false, undefined);532 }else {533 if (forms) {534 jsonString = messageFormatter.FormatMessage(err, "Form Profile Successful", true, forms);535 }else{536 jsonString = messageFormatter.FormatMessage(undefined, "No Form Profile Found", false, undefined);537 }538 }539 res.end(jsonString);540 });541}542module.exports.CreateForm = CreateForm;543module.exports.GetForm = GetForm;544module.exports.GetForms = GetForms;545module.exports.DeleteForm = DeleteForm;546module.exports.AddDynamicField = AddDynamicField;547module.exports.RemoveDynamicField = RemoveDynamicField;548module.exports.UpdateDynamicField = UpdateDynamicField;549module.exports.CreateFormSubmission = CreateFormSubmission;550module.exports.GetFormSubmission = GetFormSubmission;551module.exports.GetFormSubmissions = GetFormSubmissions;552module.exports.UpdateFormSubmission = UpdateFormSubmission;553module.exports.DeleteFormSubmission = DeleteFormSubmission;554module.exports.AddDynamicFieldSubmission = AddDynamicFieldSubmission;555module.exports.RemoveDynamicFieldSubmission = RemoveDynamicFieldSubmission;556module.exports.UpdateDynamicFieldSubmission = UpdateDynamicFieldSubmission;557module.exports.CreateFormProfile = CreateFormProfile;558module.exports.UpdateFormProfile = UpdateFormProfile;559module.exports.GetFormProfile = GetFormProfile;560module.exports.AddOrUpdateIsolatedTagForm = AddOrUpdateIsolatedTagForm;561module.exports.GetFormByTag = GetFormByTag;562module.exports.GetFormsByTags = GetFormsByTags;563module.exports.GetAllFormsByTags = GetAllFormsByTags;...

Full Screen

Full Screen

TicketTriggerService.js

Source:TicketTriggerService.js Github

copy

Full Screen

1/**2 * Created by a on 7/4/2016.3 */4var mongoose = require('mongoose');5var logger = require('dvp-common/LogHandler/CommonLogHandler.js').logger;6var TimeEntry = require('dvp-mongomodels/model/TimeEntry').TimeEntry;7var Ticket = require('dvp-mongomodels/model/Ticket').Ticket;8var User = require('dvp-mongomodels/model/User');9var Trigger = require('dvp-mongomodels/model/TicketTrigers').Trigger;10var OrganisationConfig = require('dvp-mongomodels/model/OrganisationConfig');11var messageFormatter = require('dvp-common/CommonMessageGenerator/ClientMessageJsonFormatter.js');12var q = require('q');13var triggerWorker = require('../Workers/Trigger/TriggerWorker');14function CreateTrigger(req, res) {15 logger.info("DVP-LiteTicket.CreateTrigger Internal method ");16 var company = parseInt(req.user.company);17 var tenant = parseInt(req.user.tenant);18 var jsonString;19 var data = Trigger({20 title: req.body.title,21 Active: req.body.Active,22 priority: req.body.priority,23 triggerEvent: req.body.triggerEvent,24 created_at: Date.now(),25 updated_at: Date.now(),26 company: company,27 tenant: tenant,28 conditions: req.body.conditions,29 actions: req.body.actions,30 operations: req.body.operations31 });32 data.save(function (err, trigger) {33 if (err) {34 jsonString = messageFormatter.FormatMessage(err, "Trigger create failed", false, undefined);35 }36 else {37 jsonString = messageFormatter.FormatMessage(undefined, "Trigger saved successfully", true, trigger);38 }39 res.end(jsonString);40 });41}42function GetTriggers(req, res) {43 logger.info("DVP-LiteTicket.GetTriggers Internal method ");44 var company = parseInt(req.user.company);45 var tenant = parseInt(req.user.tenant);46 var jsonString;47 Trigger.find({company: company, tenant: tenant}, function (err, triggers) {48 if (err) {49 jsonString = messageFormatter.FormatMessage(err, "Get GetTriggers Failed", false, undefined);50 res.end(jsonString);51 } else {52 jsonString = messageFormatter.FormatMessage(err, "Get GetTriggers Success", true, triggers);53 res.end(jsonString);54 }55 });56}57function GetTrigger(req, res) {58 logger.info("DVP-LiteTicket.GetTrigger Internal method ");59 var company = parseInt(req.user.company);60 var tenant = parseInt(req.user.tenant);61 var jsonString;62 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {63 if (err) {64 jsonString = messageFormatter.FormatMessage(err, "GetTrigger Failed", false, undefined);65 res.end(jsonString);66 } else {67 jsonString = messageFormatter.FormatMessage(err, "GetTrigger Success", true, trigger);68 res.end(jsonString);69 }70 });71}72function DeleteTrigger(req, res) {73 logger.info("DVP-LiteTicket.DeleteTrigger Internal method ");74 var company = parseInt(req.user.company);75 var tenant = parseInt(req.user.tenant);76 var jsonString;77 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {78 if (err) {79 jsonString = messageFormatter.FormatMessage(err, "GetTrigger Failed", false, undefined);80 res.end(jsonString);81 } else {82 if (trigger) {83 trigger.remove(function (err) {84 if (err) {85 jsonString = messageFormatter.FormatMessage(err, "Delete Trigger Failed", false, undefined);86 } else {87 jsonString = messageFormatter.FormatMessage(undefined, "Trigger successfully deleted", true, undefined);88 }89 res.end(jsonString);90 });91 } else {92 jsonString = messageFormatter.FormatMessage(undefined, "Delete Trigger Failed, Trigger object is null", false, undefined);93 res.end(jsonString);94 }95 }96 });97}98function UpdateTrigger(req, res) {99 logger.info("DVP-LiteTicket.UpdateTrigger Internal method ");100 var company = parseInt(req.user.company);101 var tenant = parseInt(req.user.tenant);102 var jsonString;103 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {104 if (err) {105 jsonString = messageFormatter.FormatMessage(err, "Get Trigger Failed", false, undefined);106 res.end(jsonString);107 } else {108 if (trigger) {109 trigger.title = req.body.title;110 trigger.Active = req.body.Active;111 trigger.priority = req.body.priority;112 trigger.triggerEvent = req.body.triggerEvent;113 trigger.updated_at = Date.now();114 trigger.conditions = req.body.conditions;115 trigger.actions = req.body.actions;116 trigger.operations = req.body.operations;117 trigger.update(trigger, function (err, newTrigger) {118 if (err) {119 jsonString = messageFormatter.FormatMessage(err, "Fail Update Trigger", false, undefined);120 }121 else {122 if (newTrigger) {123 jsonString = messageFormatter.FormatMessage(undefined, "Trigger Update Successfully", true, newTrigger);124 }125 else {126 jsonString = messageFormatter.FormatMessage(undefined, "Invalid Trigger Id.", false, newTrigger);127 }128 }129 res.end(jsonString);130 });131 } else {132 jsonString = messageFormatter.FormatMessage(err, "No Trigger Found", false, undefined);133 res.end(jsonString);134 }135 }136 });137}138function AddFilterAll(req, res) {139 logger.info("DVP-LiteTicket.AddFilterAll Internal method ");140 var company = parseInt(req.user.company);141 var tenant = parseInt(req.user.tenant);142 var jsonString;143 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {144 if (err) {145 jsonString = messageFormatter.FormatMessage(err, "Get Trigger Failed", false, undefined);146 res.end(jsonString);147 } else {148 var allFiler = {field: req.body.field, operator: req.body.operator, value: req.body.value};149 if (trigger.conditions.all && Array.isArray(trigger.conditions.all)) {150 trigger.conditions.all.push(allFiler);151 } else {152 trigger.conditions.all = [allFiler];153 }154 trigger.update(trigger, function (err, newTrigger) {155 if (err) {156 jsonString = messageFormatter.FormatMessage(err, "Add Filter All Failed", false, undefined);157 } else {158 jsonString = messageFormatter.FormatMessage(undefined, "Add Filter All Successful", true, newTrigger);159 }160 res.end(jsonString);161 });162 }163 });164}165function RemoveFilterAll(req, res) {166 logger.info("DVP-LiteTicket.RemoveFilterAll Internal method ");167 var company = parseInt(req.user.company);168 var tenant = parseInt(req.user.tenant);169 var jsonString;170 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {171 if (err) {172 jsonString = messageFormatter.FormatMessage(err, "Get Trigger Failed", false, undefined);173 res.end(jsonString);174 } else {175 for (var i = 0; i < trigger.conditions.all.length; i++) {176 if (trigger.conditions.all[i].id == req.params.filterid) {177 trigger.conditions.all.splice(i, 1);178 break;179 }180 }181 trigger.update(trigger, function (err, newTrigger) {182 if (err) {183 jsonString = messageFormatter.FormatMessage(err, "Delete Filter All Failed", false, undefined);184 } else {185 jsonString = messageFormatter.FormatMessage(undefined, "Delete Filter All Successful", true, newTrigger);186 }187 res.end(jsonString);188 });189 }190 });191}192function GetFiltersAll(req, res) {193 logger.info("DVP-LiteTicket.GetFiltersAll Internal method ");194 var company = parseInt(req.user.company);195 var tenant = parseInt(req.user.tenant);196 var jsonString;197 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {198 if (err) {199 jsonString = messageFormatter.FormatMessage(err, "Get FiltersAll Failed", false, undefined);200 } else {201 jsonString = messageFormatter.FormatMessage(undefined, "Get FiltersAll Successful", true, trigger.conditions.all);202 }203 res.end(jsonString);204 });205}206function AddFilterAny(req, res) {207 logger.info("DVP-LiteTicket.AddFilterAny Internal method ");208 var company = parseInt(req.user.company);209 var tenant = parseInt(req.user.tenant);210 var jsonString;211 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {212 if (err) {213 jsonString = messageFormatter.FormatMessage(err, "Get Trigger Failed", false, undefined);214 res.end(jsonString);215 } else {216 var anyFiler = {field: req.body.field, operator: req.body.operator, value: req.body.value};217 if (trigger.conditions.any && Array.isArray(trigger.conditions.any)) {218 trigger.conditions.any.push(anyFiler);219 } else {220 trigger.conditions.any = [anyFiler];221 }222 trigger.update(trigger, function (err, newTrigger) {223 if (err) {224 jsonString = messageFormatter.FormatMessage(err, "Add Filter Any Failed", false, undefined);225 } else {226 jsonString = messageFormatter.FormatMessage(undefined, "Add Filter Any Successful", true, newTrigger);227 }228 res.end(jsonString);229 });230 }231 });232}233function RemoveFilterAny(req, res) {234 logger.info("DVP-LiteTicket.RemoveFilterAny Internal method ");235 var company = parseInt(req.user.company);236 var tenant = parseInt(req.user.tenant);237 var jsonString;238 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {239 if (err) {240 jsonString = messageFormatter.FormatMessage(err, "Get Trigger Failed", false, undefined);241 res.end(jsonString);242 } else {243 for (var i = 0; i < trigger.conditions.any.length; i++) {244 if (trigger.conditions.any[i].id == req.params.filterid) {245 trigger.conditions.any.splice(i, 1);246 break;247 }248 }249 trigger.update(trigger, function (err, newTrigger) {250 if (err) {251 jsonString = messageFormatter.FormatMessage(err, "Delete Filter Any Failed", false, undefined);252 } else {253 jsonString = messageFormatter.FormatMessage(undefined, "Delete Filter Any Successful", true, newTrigger);254 }255 res.end(jsonString);256 });257 }258 });259}260function GetFiltersAny(req, res) {261 logger.info("DVP-LiteTicket.GetFiltersAny Internal method ");262 var company = parseInt(req.user.company);263 var tenant = parseInt(req.user.tenant);264 var jsonString;265 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {266 if (err) {267 jsonString = messageFormatter.FormatMessage(err, "Get FiltersAny Failed", false, undefined);268 } else {269 jsonString = messageFormatter.FormatMessage(undefined, "Get FiltersAny Successful", true, trigger.conditions.any);270 }271 res.end(jsonString);272 });273}274function AddAction(req, res) {275 logger.info("DVP-LiteTicket.AddAction Internal method ");276 var company = parseInt(req.user.company);277 var tenant = parseInt(req.user.tenant);278 var jsonString;279 Trigger.findOneAndUpdate({_id: req.params.id, company: company, tenant: tenant}, {280 $addToSet: {281 actions: {282 field: req.body.field,283 value: req.body.value284 }285 }286 }, function (err, actions) {287 if (err) {288 jsonString = messageFormatter.FormatMessage(err, "Add Action Failed", false, undefined);289 } else {290 jsonString = messageFormatter.FormatMessage(undefined, "Add Action Successful", true, actions);291 }292 res.end(jsonString);293 });294}295function RemoveAction(req, res) {296 logger.info("DVP-LiteTicket.RemoveAction Internal method ");297 var company = parseInt(req.user.company);298 var tenant = parseInt(req.user.tenant);299 var jsonString;300 Trigger.findOneAndUpdate({_id: req.params.id, company: company, tenant: tenant}, {301 $pull: {302 actions: {303 _id: req.params.actionid304 }305 }306 }, function (err, actions) {307 if (err) {308 jsonString = messageFormatter.FormatMessage(err, "Delete Action Failed", false, undefined);309 } else {310 jsonString = messageFormatter.FormatMessage(undefined, "Delete Action Successful", true, actions);311 }312 res.end(jsonString);313 });314}315function GetActions(req, res) {316 logger.info("DVP-LiteTicket.GetActions Internal method ");317 var company = parseInt(req.user.company);318 var tenant = parseInt(req.user.tenant);319 var jsonString;320 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {321 if (err) {322 jsonString = messageFormatter.FormatMessage(err, "Get Actions Failed", false, undefined);323 } else {324 jsonString = messageFormatter.FormatMessage(undefined, "Get Actions Successful", true, trigger.actions);325 }326 res.end(jsonString);327 });328}329function AddOperations(req, res) {330 logger.info("DVP-LiteTicket.AddOperations Internal method ");331 var company = parseInt(req.user.company);332 var tenant = parseInt(req.user.tenant);333 var jsonString;334 Trigger.findOneAndUpdate({_id: req.params.id, company: company, tenant: tenant}, {335 $addToSet: {336 operations: {337 name: req.body.name,338 field: req.body.field,339 value: req.body.value340 }341 }342 }, function (err, operations) {343 if (err) {344 jsonString = messageFormatter.FormatMessage(err, "Add Operations Failed", false, undefined);345 } else {346 jsonString = messageFormatter.FormatMessage(undefined, "Add Operations Successful", true, operations);347 }348 res.end(jsonString);349 });350}351function RemoveOperations(req, res) {352 logger.info("DVP-LiteTicket.RemoveOperations Internal method ");353 var company = parseInt(req.user.company);354 var tenant = parseInt(req.user.tenant);355 var jsonString;356 Trigger.findOneAndUpdate({_id: req.params.id, company: company, tenant: tenant}, {357 $pull: {358 operations: {359 _id: req.params.operationid360 }361 }362 }, function (err, operations) {363 if (err) {364 jsonString = messageFormatter.FormatMessage(err, "Delete Operations Failed", false, undefined);365 } else {366 jsonString = messageFormatter.FormatMessage(undefined, "Delete Operations Successful", true, operations);367 }368 res.end(jsonString);369 });370}371function GetOperations(req, res) {372 logger.info("DVP-LiteTicket.GetOperations Internal method ");373 var company = parseInt(req.user.company);374 var tenant = parseInt(req.user.tenant);375 var jsonString;376 Trigger.findOne({_id: req.params.id, company: company, tenant: tenant}, function (err, trigger) {377 if (err) {378 jsonString = messageFormatter.FormatMessage(err, "Get Operations Failed", false, undefined);379 } else {380 jsonString = messageFormatter.FormatMessage(undefined, "Get Operations Successful", true, trigger.operations);381 }382 res.end(jsonString);383 });384}385var getOrgConfig = function (company, tenant) {386 return triggerWorker.GetOrgConfig(company,tenant);387 /*var deferred = q.defer();388 try {389 OrganisationConfig.findOne({company: company, tenant: tenant}, function (err, config) {390 try{391 triggerWorker.TriggerConfig.push( key: item.company,392 value: item);393 }catch (ex){394 }395 deferred.resolve(config);396 });397 }398 catch (ex) {399 deferred.reject(ex);400 }401 return deferred.promise;*/402};403module.exports.GetTriggerConfiguration = function (req, res) {404 logger.info("GetTriggerConfiguration Internal method ");405 var company = parseInt(req.user.company);406 var tenant = parseInt(req.user.tenant);407 var jsonString;408 getOrgConfig(company, tenant).then(function (config) {409 if (config) {410 jsonString = messageFormatter.FormatMessage(undefined, "GetTrigger Configuration successfully", true, config);411 }412 else {413 jsonString = messageFormatter.FormatMessage(undefined, "Get TriggerCon figuration failed", false, undefined);414 }415 res.end(jsonString);416 }), function (err) {417 jsonString = messageFormatter.FormatMessage(err, "Get Trigger Configuration failed", false, undefined);418 res.end(jsonString);419 };420};421module.exports.CreateTriggerConfiguration = function (req, res) {422 logger.info("CreateTriggerConfiguration Internal method ");423 var company = parseInt(req.user.company);424 var tenant = parseInt(req.user.tenant);425 var jsonString;426 /*var organisationConfig = OrganisationConfig({427 created_at: Date.now(),428 updated_at: Date.now(),429 company: company,430 tenant: tenant,431 highPriority_match: req.body.highPriorityMatch432 });*/433 OrganisationConfig.update({company: company, tenant: tenant}, {434 $set: {435 "company": company,436 "tenant": tenant,437 "highPriority_match":req.body.highPriorityMatch,438 "created_at": Date.now(),439 "updated_at": Date.now()440 }441 }, {upsert: true}, function (err, config) {442 if (err) {443 jsonString = messageFormatter.FormatMessage(err, "Create Trigger Configuration failed", false, undefined);444 }445 else {446 jsonString = messageFormatter.FormatMessage(undefined, "Create Trigger Configuration successfully", true, config);447 }448 getOrgConfig(company, tenant);449 res.end(jsonString);450 });451 /*organisationConfig.save(function (err, config) {452 if (err) {453 jsonString = messageFormatter.FormatMessage(err, "Create Trigger Configuration failed", false, undefined);454 }455 else {456 jsonString = messageFormatter.FormatMessage(undefined, "Create Trigger Configuration successfully", true, config);457 }458 getOrgConfig(company, tenant);459 res.end(jsonString);460 });*/461};462module.exports.UpdateTriggerConfiguration = function (req, res) {463 logger.info("UpdateTriggerConfiguration Internal method ");464 var company = parseInt(req.user.company);465 var tenant = parseInt(req.user.tenant);466 var jsonString;467 OrganisationConfig.findOne({company: company, tenant: tenant}, function (err, trigger) {468 if (err) {469 jsonString = messageFormatter.FormatMessage(err, "Get Organisation Trigger Config Failed", false, undefined);470 res.end(jsonString);471 } else {472 if (trigger) {473 trigger.highPriority_match = req.body.highPriorityMatch;474 trigger.update(trigger, function (err, newTrigger) {475 if (err) {476 jsonString = messageFormatter.FormatMessage(err, "Fail Update Organisation Trigger Config", false, undefined);477 }478 else {479 if (newTrigger) {480 jsonString = messageFormatter.FormatMessage(undefined, "Organisation Trigger Config Update Successfully", true, newTrigger);481 }482 else {483 jsonString = messageFormatter.FormatMessage(undefined, "Invalid Organisation Trigger Config.", false, newTrigger);484 }485 getOrgConfig(company, tenant);486 }487 res.end(jsonString);488 });489 } else {490 jsonString = messageFormatter.FormatMessage(err, "No Organisation Trigger Config Found", false, undefined);491 res.end(jsonString);492 }493 }494 });495};496module.exports.DeleteTriggerConfiguration = function (req, res) {497 logger.info("UpdateTriggerConfiguration Internal method ");498 var company = parseInt(req.user.company);499 var tenant = parseInt(req.user.tenant);500 var jsonString;501 OrganisationConfig.findOne({company: company, tenant: tenant}, function (err, trigger) {502 if (err) {503 jsonString = messageFormatter.FormatMessage(err, "Get Organisation Trigger Config Failed", false, undefined);504 res.end(jsonString);505 } else {506 if (trigger) {507 trigger.remove(function (err) {508 if (err) {509 jsonString = messageFormatter.FormatMessage(err, "Fail Delete Organisation Trigger Config", false, undefined);510 }511 else {512 jsonString = messageFormatter.FormatMessage(undefined, "Organisation Trigger Config Delete Successfully", true, newTrigger);513 }514 getOrgConfig(company, tenant);515 res.end(jsonString);516 });517 } else {518 jsonString = messageFormatter.FormatMessage(err, "No Organisation Trigger Config Found", false, undefined);519 res.end(jsonString);520 }521 }522 });523};524module.exports.CreateTrigger = CreateTrigger;525module.exports.GetTriggers = GetTriggers;526module.exports.GetTrigger = GetTrigger;527module.exports.UpdateTrigger = UpdateTrigger;528module.exports.DeleteTrigger = DeleteTrigger;529module.exports.AddFilterAll = AddFilterAll;530module.exports.RemoveFilterAll = RemoveFilterAll;531module.exports.GetFiltersAll = GetFiltersAll;532module.exports.AddFilterAny = AddFilterAny;533module.exports.RemoveFilterAny = RemoveFilterAny;534module.exports.GetFiltersAny = GetFiltersAny;535module.exports.AddAction = AddAction;536module.exports.RemoveAction = RemoveAction;537module.exports.GetActions = GetActions;538module.exports.AddOperations = AddOperations;539module.exports.RemoveOperations = RemoveOperations;...

Full Screen

Full Screen

MessageFormatter.js

Source:MessageFormatter.js Github

copy

Full Screen

1//****************************************************************************2// Copyright 2018 BlackBerry. All Rights Reserved.3//4// You must obtain a license from and pay any applicable license fees to5// BlackBerry before you may reproduce, modify or distribute this software, or6// any work that includes all or part of this software.7//8"use strict";9/**10 * A message formatter which formats the content message used in the user11 * interface.12 *13 * @memberof Support.Util14 * @class MessageFormatter15 */16(function (MessageFormatter) {17 // This function will always be called with the correct global context to18 // which this module may export.19 var global = this;20 // Where do we place the module? Do we have an exports object to use?21 if (typeof exports !== 'undefined') {22 if( typeof module !== 'undefined' && module.exports ) {23 exports = module.exports = MessageFormatter();24 }25 exports.MessageFormatter = MessageFormatter();26 }27 else {28 global.MessageFormatter = MessageFormatter();29 }30}).call(this, function() {31 const IMG_DELIVERED_PARTIAL = "img/delivered_partial.png";32 const IMG_DELIVERED = "img/delivered.png";33 const IMG_READ_PARTIAL = "img/read_partial.png";34 const IMG_READ = "img/read.png";35 const IMG_GREY_PELLET = "img/grey_pellet.png";36 const IMG_YELLOW_PELLET = "img/yellow_pellet.png";37 const IMG_FAILED = "img/failed.png";38 const IMG_RETRACT = "img/msg_retract.png";39 const IMG_SENT = "img/sent.png";40 const IMG_LOCKER_CHAT_BUBBLE = "img/locker_chat_bubble.png";41 const IMG_DEFAULT_AVATAR = "img/defaultAvatar.png";42 const widgetURI = (document._currentScript || document.currentScript).src;43 const m_basePath = widgetURI.substring(0, widgetURI.lastIndexOf("/") + 1);44 /**45 * Construct a MessageFormatter. This is used to produce formatted content for46 * a message.47 * @param {object} contactManager The contact manager used to display48 * information about contacts in bubbles.49 */50 var MessageFormatter = function(contactManager) {51 this.contactManager = contactManager;52 };53 MessageFormatter.prototype = Object.create(Object.prototype);54 MessageFormatter.prototype.constructor = MessageFormatter;55 /**56 * Get the username for a registration ID. If there is a name registered57 * for the user, it will be used. Otherwise, the registration ID in string58 * form will be used.59 *60 * @param {object} message A message object to get the user name for.61 * @returns {string} User display name.62 */63 MessageFormatter.prototype.getUserName = function(message) {64 const contactName = this.contactManager.getDisplayName(message.sender);65 return contactName || message.sender.toString();66 };67 /**68 * Get the avatar for a message. If there is an avatar registered for the69 * contact, it will be used. Otherwise, the default avatar will be used.70 * @param {object} message A message object to get the user avatar URL for.71 * @returns {string} User avatar URL.72 */73 MessageFormatter.prototype.getMessageAvatar = function(message) {74 const avatar = this.contactManager.getUserAvatar(message.sender);75 return avatar || m_basePath + IMG_DEFAULT_AVATAR;76 };77 /**78 * Get an image to represent the state of chat message79 * @param {BBMEnterprise.Messenger.ChatMessage} chatMessage80 * The chatMessage that message state belongs to81 * @returns {string} The URL of the message state image82 */83 MessageFormatter.prototype.getMessageStateImage = function(chatMessage) {84 var isIncoming = chatMessage.isIncoming;85 if (isIncoming && chatMessage.isUnverified) {86 // Check if the message is unverified.87 return m_basePath + IMG_LOCKER_CHAT_BUBBLE;88 }89 var state = chatMessage.state.value;90 var isPartial = chatMessage.state.isPartial;91 var isRecalled = chatMessage.isRecalled;92 var isOneToOneChat = chatMessage.isOneToOne;93 if (isRecalled) {94 // Check if the message state is recalled95 return m_basePath + IMG_RETRACT;96 } else if (state ===97 BBMEnterprise.Messenger.ChatMessage.StateValue.Sent) {98 // Check if the message state is sent99 return m_basePath + IMG_SENT;100 } else if (state ===101 BBMEnterprise.Messenger.ChatMessage.StateValue.Delivered) {102 // Check if the message state is delivered103 if (isIncoming) {104 return m_basePath + IMG_YELLOW_PELLET;105 } else if (!isOneToOneChat) {106 return m_basePath +107 (isPartial ? IMG_DELIVERED_PARTIAL : IMG_DELIVERED);108 } else {109 return m_basePath + IMG_DELIVERED;110 }111 } else if (state ===112 BBMEnterprise.Messenger.ChatMessage.StateValue.Read) {113 // Check if the message state is read114 if (isIncoming) {115 return m_basePath + IMG_GREY_PELLET;116 } else if (!isOneToOneChat) {117 return m_basePath + (isPartial ? IMG_READ_PARTIAL : IMG_READ);118 } else {119 return m_basePath + IMG_READ;120 }121 } else if (state == "Failed" && isOneToOneChat) {122 // don't show failed messages for multichats123 return m_basePath + IMG_FAILED;124 }125 // Default image URL should be empty.126 return '';127 };128 /**129 * Retrieve a textual description of the content of a message.130 *131 * @param {BBMEnterprise.Messenger.ChatMessage} message132 * The message containing data to retrieve.133 *134 * @returns {string} A content string for the message.135 */136 MessageFormatter.prototype.getMessageText = function(message) {137 if (message.isRecalled) {138 return 'Message retracted.';139 } else {140 switch (message.tag) {141 case MessageFormatter.Tag.File:142 case MessageFormatter.Tag.Picture:143 case MessageFormatter.Tag.Text:144 return message.content;145 case BBMEnterprise.Messenger.ChatMessage.ReservedTag.Join:146 return this.contactManager.getDisplayName(message.sender) 147 + ' joined the chat.';148 case BBMEnterprise.Messenger.ChatMessage.ReservedTag.Leave:149 return this.contactManager.getDisplayName(message.sender)150 + ' left the chat.';151 case BBMEnterprise.Messenger.ChatMessage.ReservedTag.Remove:152 return this.contactManager.getDisplayName(message.sender)153 + ' removed '154 + this.contactManager.getDisplayName(message.data.regId)155 + ' from the chat.';156 case BBMEnterprise.Messenger.ChatMessage.ReservedTag.Admin:157 if (message.data && message.data.regId) {158 return this.contactManager.getDisplayName(message.data.regId) +159 (message.data.promotion === true160 ? ' is now an admin.' 161 : ' is no longer an admin.');162 } else {163 console.warn("MessageFormatter: missing expected data in admin"164 + " message.");165 return '';166 }167 case BBMEnterprise.Messenger.ChatMessage.ReservedTag.Shred:168 return this.contactManager.getDisplayName(message.sender)169 + ' retracted the chat.';170 case BBMEnterprise.Messenger.ChatMessage.ReservedTag.Subject:171 return this.contactManager.getDisplayName(message.sender)172 + ' changed the chat subject.';173 default:174 return this.contactManager.getDisplayName(message.sender)175 + `sent an item (Tag: ${message.tag}) that is not supported.`;176 }177 }178 };179 /**180 * Return whether a message is a status message.181 *182 * @param {BBMEnterprise.Messenger.ChatMessage} message183 * The message to check.184 *185 * @returns {boolean} True if and only if the message is a status message.186 */187 MessageFormatter.prototype.getIsStatusMessage = function(message) {188 return message.tag !== MessageFormatter.Tag.Text &&189 message.tag !== MessageFormatter.Tag.File &&190 message.tag !== MessageFormatter.Tag.Picture;191 };192 /**193 * Return whether a message is a picture.194 *195 * @param {BBMEnterprise.Messenger.ChatMessage} message196 * The message to check.197 *198 * @returns {boolean} True if and only if the message is a picture.199 */200 MessageFormatter.prototype.getIsPictureMessage = function(message) {201 return message.tag === MessageFormatter.Tag.Picture;202 };203 /**204 * Return whether a message is a file transfer.205 *206 * @param {BBMEnterprise.Messenger.ChatMessage} message207 * The message to check.208 *209 * @returns {boolean} True if and only if the message is a file transfer.210 */211 MessageFormatter.prototype.getIsFileMessage = function(message) {212 return message.tag === MessageFormatter.Tag.File;213 };214 // :: ----------------------------------------------------------------------215 // :: Data Members216 MessageFormatter.Tag = {217 Text: 'Text',218 Picture: 'Picture',219 File: 'File'220 };221 return MessageFormatter;222});...

Full Screen

Full Screen

message-formatter.js

Source:message-formatter.js Github

copy

Full Screen

...11 if ( arguments.length === 3 ) {12 expected = variables;13 variables = undefined;14 }15 this.equal( Globalize( locale ).messageFormatter( path )( variables ), expected );16};17QUnit.assert.messageBundlePresence = function( fn ) {18 this.throws( fn, function E_MISSING_MESSAGE_BUNDLE( error ) {19 return error.code === "E_MISSING_MESSAGE_BUNDLE" &&20 "locale" in error;21 }, "Expected \"E_MISSING_MESSAGE_BUNDLE\" to be thrown" );22};23QUnit.module( ".messageFormatter( path )", {24 setup: function() {25 Globalize.load( likelySubtags );26 Globalize.load( plurals );27 Globalize.loadMessages({28 root: {29 amen: "Amen"30 },31 de: {},32 en: {33 greetings: {34 hello: "Hello",35 helloArray: "Hello, {0}",36 helloArray2: "Hello, {0} and {1}",37 helloName: "Hello, {name}"38 },39 like: [40 "{count, plural, offset:1",41 " =0 {Be the first to like this}",42 " =1 {You liked this}",43 " one {You and {someone} liked this}",44 " other {You and # others liked this}",45 "}"46 ],47 party: [48 "{hostGender, select,",49 " female {{host} invites {guest} to her party}",50 " male {{host} invites {guest} to his party}",51 " other {{host} invites {guest} to their party}",52 "}"53 ],54 task: [55 "You have {0, plural,",56 " one {one task}",57 " other {# tasks}",58 "} remaining"59 ]60 },61 "en-GB": {},62 fr: {},63 pt: {64 amen: "Amém"65 },66 "pt-PT": {},67 zh: {68 amen: "阿门"69 }70 });71 },72 teardown: util.resetCldrContent73});74QUnit.test( "should pass test's prerequisites", function( assert ) {75 var sr = new Globalize( "sr" );76 // OBS: Ensure `sr` cldr/main dataset hasn't being loaded elsewhere. It's a prerequisites for77 // the below messageBundlePresence test.78 assert.deepEqual( sr.cldr.attributes.bundle, null, "`sr` cldr/main dataset cannot be loaded" );79});80QUnit.test( "should validate parameters", function( assert ) {81 util.assertParameterPresence( assert, "path", function() {82 Globalize( "en" ).messageFormatter();83 });84 util.assertPathParameter( assert, "path", function( invalidValue ) {85 return function() {86 Globalize( "en" ).messageFormatter( invalidValue );87 };88 });89});90QUnit.test( "should validate messages", function( assert ) {91 assert.messageBundlePresence(function() {92 Globalize( "sr" ).messageFormatter( "path" );93 });94 util.assertMessagePresence( assert, "non-existent/path", function() {95 Globalize( "en" ).messageFormatter( "non-existent/path" );96 });97 util.assertMessageType( assert, "invalid-message", function( invalidValue ) {98 Globalize.loadMessages({99 en: {100 "invalid-message": invalidValue101 }102 });103 return function() {104 Globalize( "en" ).messageFormatter( "invalid-message" );105 };106 });107});108QUnit.test( "should return the loaded translation", function( assert ) {109 assert.messageFormatter( "pt", "amen", "Amém" );110 assert.messageFormatter( "zh", "amen", "阿门" );111});112QUnit.test( "should traverse the translation data", function( assert ) {113 assert.messageFormatter( "en", "greetings/hello", "Hello" );114 assert.messageFormatter( "en", [ "greetings", "hello" ], "Hello" );115});116QUnit.test( "should return inherited translation if cldr/unresolved is loaded", function( assert ) {117 assert.messageFormatter( "en", "amen", "Amen" );118 assert.messageFormatter( "de", "amen", "Amen" );119 assert.messageFormatter( "en-GB", "amen", "Amen" );120 assert.messageFormatter( "fr", "amen", "Amen" );121 assert.messageFormatter( "pt-PT", "amen", "Amém" );122});123QUnit.test( "should support ICU message format", function( assert ) {124 var like;125 // Var replacement126 assert.messageFormatter( "en", "greetings/helloArray", [ "Beethoven" ], "Hello, Beethoven" );127 assert.messageFormatter( "en", "greetings/helloArray", "Beethoven", "Hello, Beethoven" );128 assert.messageFormatter( "en", "greetings/helloArray2", [ "Beethoven", "Mozart" ],129 "Hello, Beethoven and Mozart" );130 assert.equal(131 Globalize( "en" ).messageFormatter( "greetings/helloArray2" )( "Beethoven", "Mozart" ),132 "Hello, Beethoven and Mozart"133 );134 assert.messageFormatter( "en", "greetings/helloName", {135 name: "Beethoven"136 }, "Hello, Beethoven" );137 // Plural138 assert.messageFormatter( "en", "task", 123, "You have 123 tasks remaining" );139 // Select140 assert.messageFormatter( "en", "party", {141 guest: "Mozart",142 host: "Beethoven",143 hostGender: "male"144 }, "Beethoven invites Mozart to his party" );145 // Plural offset146 like = new Globalize( "en" ).messageFormatter( "like" );147 assert.equal( like({ count: 0 }), "Be the first to like this" );148 assert.equal( like({ count: 1 }), "You liked this" );149 assert.equal( like({150 count: 2,151 someone: "Beethoven"152 }), "You and Beethoven liked this" );153 assert.equal( like({ count: 3 }), "You and 2 others liked this" );154});155// Reference #473156QUnit.test( "should NOT merge array data", function( assert ) {157 // Re-loading a message that uses array syntax.158 Globalize.loadMessages({159 en: {160 task: [161 "You have {0, plural,",162 " one {one task}",163 " other {# tasks}",164 "} remaining"165 ]166 }167 });168 assert.messageFormatter( "en", "task", 123, "You have 123 tasks remaining" );169});...

Full Screen

Full Screen

MessageFormatter.spec.js

Source:MessageFormatter.spec.js Github

copy

Full Screen

1import MessageFormatter from '../MessageFormatter';2describe('#MessageFormatter', () => {3 describe('content with links', () => {4 it('should format correctly', () => {5 const message =6 'Chatwoot is an opensource tool. [Chatwoot](https://www.chatwoot.com)';7 expect(new MessageFormatter(message).formattedMessage).toMatch(8 '<p>Chatwoot is an opensource tool. <a rel="noreferrer noopener nofollow" href="https://www.chatwoot.com" class="link" title="" target="_blank">Chatwoot</a></p>'9 );10 });11 it('should format correctly', () => {12 const message =13 'Chatwoot is an opensource tool. https://www.chatwoot.com';14 expect(new MessageFormatter(message).formattedMessage).toMatch(15 '<p>Chatwoot is an opensource tool. <a rel="noreferrer noopener nofollow" href="https://www.chatwoot.com" class="link" title="" target="_blank">https://www.chatwoot.com</a></p>'16 );17 });18 });19 describe('parses heading to strong', () => {20 it('should format correctly', () => {21 const message = '### opensource \n ## tool';22 expect(new MessageFormatter(message).formattedMessage).toMatch(23 '<strong>opensource</strong><strong>tool</strong>'24 );25 });26 });27 describe('tweets', () => {28 it('should return the same string if not tags or @mentions', () => {29 const message = 'Chatwoot is an opensource tool';30 expect(new MessageFormatter(message).formattedMessage).toMatch(message);31 });32 it('should add links to @mentions', () => {33 const message =34 '@chatwootapp is an opensource tool thanks @longnonexistenttwitterusername';35 expect(new MessageFormatter(message, true).formattedMessage).toMatch(36 '<p><a href="http://twitter.com/chatwootapp" target="_blank" rel="noreferrer nofollow noopener">@chatwootapp</a> is an opensource tool thanks @longnonexistenttwitterusername</p>'37 );38 });39 it('should add links to #tags', () => {40 const message = '#chatwootapp is an opensource tool';41 expect(new MessageFormatter(message, true).formattedMessage).toMatch(42 '<p><a href="https://twitter.com/hashtag/chatwootapp" target="_blank" rel="noreferrer nofollow noopener">#chatwootapp</a> is an opensource tool</p>'43 );44 });45 });46 describe('plain text content', () => {47 it('returns the plain text without HTML', () => {48 const message =49 '<b>Chatwoot is an opensource tool. https://www.chatwoot.com</b>';50 expect(new MessageFormatter(message).plainText).toMatch(51 'Chatwoot is an opensource tool. https://www.chatwoot.com'52 );53 });54 });...

Full Screen

Full Screen

messageFormatterMixin.js

Source:messageFormatterMixin.js Github

copy

Full Screen

1import MessageFormatter from '../helpers/MessageFormatter';2import DOMPurify from 'dompurify';3export default {4 methods: {5 formatMessage(message, isATweet) {6 const messageFormatter = new MessageFormatter(message, isATweet);7 return messageFormatter.formattedMessage;8 },9 getPlainText(message, isATweet) {10 const messageFormatter = new MessageFormatter(message, isATweet);11 return messageFormatter.plainText;12 },13 truncateMessage(description = '') {14 if (description.length < 100) {15 return description;16 }17 return `${description.slice(0, 97)}...`;18 },19 stripStyleCharacters(message) {20 return DOMPurify.sanitize(message, {21 FORBID_TAGS: ['style'],22 FORBID_ATTR: [23 'id',24 'class',25 'style',26 'bgcolor',27 'valign',28 'width',29 'face',30 'color',31 'height',32 'lang',33 'align',34 'size',35 'border',36 ],37 });38 },39 },...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful