Guest User

Untitled

a guest
Jun 13th, 2018
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.88 KB | None | 0 0
  1. var express = require("express");
  2. var db = require("../models");
  3. const Op = db.Sequelize.Op
  4. var router = express.Router();
  5. // These three lines should be put outside of the fuction
  6. // on top of the file
  7. let configs = {};
  8. //if the process is in development it will refer to secrets
  9. //but if its production then it will refer to heroku's secrets section.
  10. //and the production heroku refers to the tokens acountSid and authToken
  11. if (process.env.NODE_ENV !== 'production') {
  12. configs = require('../config/secrets.js')
  13. }
  14. const accountSid = process.env.TWILLIO_ACCOUNTSID || configs.twilio_accountSid;
  15. const authToken = process.env.TWILLIO_AUTHTOKEN || configs.twilio_authtoken;
  16. const client = require('twilio')(accountSid, authToken);
  17. var schedule = require('node-schedule');
  18.  
  19. const phoneBook = {};
  20. // User APIs
  21. // get all users
  22. // get all employees
  23. // get all employers
  24. //TONY I WANT YOU TO UNDERSTAND AND ADD NOTES TO EVERY CODE, AND BRANCH
  25. //FIX THE DAMN STYLING ASAP PLEASE BOY
  26. //first off change the damn style all together, for real fuck vuetify or use its cdn
  27. // damn it as a dream,, add text bitcoin api payment option to hey earl
  28.  
  29. //you need to make it way more functional, the name of the user shit needs to look good
  30.  
  31. //add the links to the heroku add you added named OPBEAT
  32.  
  33.  
  34. //adding cron scheduling to the mysql posts
  35. var j = schedule.scheduleJob('30 4 * * *', function(){
  36. // it should trigger ever day at 4:30 in the morning
  37. // and check if the the posts are older than 7 days
  38. const today = new Date();
  39. // new date() is Js for today's time and date
  40. // below is adding miliseconds to seconds to minutes to hours to days, less than todays date
  41. // and if its a less than the date number seven days ago, then it will delete the post,
  42. const predicate = new Date(today - 7 * 24 * 60 * 60 * 1000);
  43. db.JobPost.destroy({
  44. where: {
  45. createdAt: {
  46. //below is a sequalize key thats why its in brakets, that means less than the predicate
  47. //so it deletes or destroys it from the data base
  48. [Op.lt]: predicate,
  49. }
  50. }
  51. })
  52.  
  53. })
  54.  
  55. router.post('/textit/posts', function (req, res) {
  56. var phone = req.body.phone;
  57. var zipCode = req.body.text;
  58.  
  59. // Step1: get the first jobPost data with sequelize near the zip code
  60. db.JobPost.findOne({
  61. where: {
  62. locationZip: zipCode
  63. },
  64. order: [
  65. ['createdAt', 'DESC']
  66. ]
  67. }).then(post => {
  68. console.log(post);
  69. var text = `Pay Amount: ${post.payAmount}
  70. Work Description: ${post.description}
  71. Phone number: ${post.phone}`
  72. // Step2: send the jobpost back to users
  73. client.messages.create({
  74. body: text, // here is your text message
  75. to: phone, // replace this with user's phone number
  76. from: '+12544002317',
  77. })
  78. .then((message) => {
  79. //this particular res.json isn't needed for the file as much
  80. //as it ends the file, and isn't left hangin
  81. res.json({
  82. message: 'Text has been sent'
  83. })
  84. }).catch(err => {
  85. console.log(err)
  86. })
  87. }).catch(err => {
  88. console.log(err)
  89. })
  90. })
  91.  
  92.  
  93. router.post('/sms', function (req, res) {
  94. // const question = req.params.question;
  95. const value = req.body.Body.trim().toLowerCase();
  96. const phone = req.body.From;
  97. // destructuring of objects
  98. let { nextStep: currentStep = 0, viewing } = phoneBook[phone] || {};
  99. currentStep = parseInt(currentStep);
  100.  
  101. if (value === 'hello' || value === 'reset' || value === 'hey earl') {
  102. phoneBook[phone] = { nextStep: 0, viewing: false };
  103. currentStep = 0;
  104. viewing = false;
  105. }
  106. console.log(value, phone);
  107. console.log(`The current step is ${currentStep}`);
  108. if (!value) {
  109. res.status(400).json({
  110. message: 'To use Hey Earl List, please type the work HELLO or HEY EARL'
  111. });
  112. return;
  113. }
  114.  
  115. switch (currentStep) {
  116. case 0:
  117. sendTextMessage(res, currentStep += 1, "Post or View?", phone)();
  118. break;
  119. case 1:
  120. if (value !== 'post' && value !== 'view') {
  121. sendTextMessage(res, currentStep, "Please type POST or VIEW.", phone)();
  122. break;
  123. }
  124. if (value === 'view') {
  125. sendTextMessage(res, currentStep += 1, 'What is the zip code?', phone, true)();
  126. break;
  127. }
  128. if (value === 'post') {
  129. sendTextMessage(res, currentStep += 1, 'If you want a job done text EMPLOYER. If you are offering to work text EMPLOYEE', phone)();
  130. res.end();
  131. break;
  132. }
  133. case 2:
  134. if (viewing) {
  135. const isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value)
  136. if (isValidZip) {
  137. db.JobPost.findAll({
  138. where: {
  139. locationZip: value
  140. }
  141. })
  142. .then(posts => {
  143. const postMsgs = posts
  144. .map((post, idx) => (
  145. `Post ${idx + 1}:\n
  146. Phone: ${post.phone},\n
  147. Description: ${post.description},\n
  148. Hourly Pay: ${post.payAmount},\n
  149. Has Transportation: ${post.hasCar}\n
  150. `
  151. ))
  152. .join('\n')
  153. sendTextMessage(res, currentStep += 1, postMsgs || 'No post in this area!', phone)()
  154. })
  155. break;
  156. } else {
  157. sendTextMessage(res, currentStep, 'Invalid zip code', phone)();
  158. break;
  159. }
  160. }
  161. // Do a checking on the incoming value to see whether the value is waht you are
  162. // expecting. Else, you DO NOT change the current step, instead, you just keep
  163. // sending the same message until you get what you ask for! e.g.
  164. /**
  165. * if (value !== 'employer' || value !== 'employee') {
  166. * 1. send a message to tell the user he/she is a dumbass
  167. * 2. end the request by return res.end()
  168. * }
  169. * ADD JOB DESCRIPTION TO VIEW. with a question asking if they would like to view another zip
  170. * IN THE BRANCH THATS USING TEXTIT
  171. *
  172. * HOW DO I GET IT TO DELETE EVERY WEEK EACH POSTING, AND MAYBE ONLY OFFER AN EMPTY
  173. * LISTING THAT SAYS THERE AREN'T NO LISTINGS
  174. *
  175. * HOW TO DELETE FROM MY EXISTING DATABASE. TO SET IT UP FOR FUTURE POSTS.
  176. *
  177. */
  178. console.log(value, value === 'employee');
  179. if (value !== 'employer' && value !== 'employee') {
  180. sendTextMessage(res, currentStep, "Send only the word 'EMPLOYEE' or 'EMPLOYER'", phone)();
  181. return res.end()
  182. }
  183.  
  184. db.JobPost.create({
  185. phone,
  186. role: value
  187. })
  188. .then(post => {
  189. sendTextMessage(res, currentStep += 1, 'What is your zip code?', phone)()
  190. res.json({
  191. hasDone: post.hasFinishedCreation()
  192. })
  193. })
  194. .catch(err => console.log(err.message));
  195. break
  196. case 3:
  197. // if(value regex the if statement does doesnt add +1 step // Using regex to check whether the value is a valid zip code
  198. // var isValidZip = /(^\d{5}(-\d{4})?$/.test("76652");
  199. updatePost(phone, res, 'locationZip', value, sendTextMessage(res, currentStep += 1, 'Briefly give a few words about the work you are offering?', phone));
  200. break;
  201. case 4:
  202. updatePost(phone, res, 'description', value, sendTextMessage(res, currentStep += 1, 'Hourly amount offered or desired? Please reply with a number only.', phone));
  203. break;
  204. case 5:
  205. updatePost(phone, res, 'payAmount', value, sendTextMessage(res, currentStep += 1, 'Reply *YES* if you offer transportation for your workers or if you have transportation to get to gig location. Text *NO* if you need transportation.', phone));
  206. break;
  207. case 6:
  208. if (value !== 'yes' && value !== 'no') {
  209. sendTextMessage(res, currentStep, "Send only 'YES' or 'NO'", phone)();
  210. return res.end()
  211. }
  212. // Sequelize wants a boolean so this is our way of giving it a boolean ,, the value will still be a string
  213. const answer = value === 'yes';
  214. updatePost(phone, res, 'hasCar', answer, sendTextMessage(res, 0, 'Thank you for using hey earl, your post will be public for a week! You can post again after that.', phone));
  215. break;
  216. default:
  217. res.status(401).json({
  218. message: 'Not valid'
  219. });
  220. break;
  221. }
  222. });
  223.  
  224. /**
  225. * updatePost
  226. * A helper method to update value of a jobPost through user's phone number.
  227. * @param {number} phone - User's phone number
  228. * @param {object} res - res object of express router
  229. * @param {string} key - which key you want to update for a jobPost
  230. * @param {any} value - what is the new value of that jobPost's key
  231. * @returns {Promise.<TResult>}
  232. */
  233. function updatePost(phone, res, key, value, cb) {
  234. // If you want to always have only ONE record in the database of a jobpost with that phone
  235. // number, use findOrCreate instead of findOne. findOne will create a new record in the database
  236. // each time a 'role' question got answered
  237. return db.JobPost.findOne({
  238. where: {
  239. phone
  240. },
  241. order: [
  242. ['createdAt', 'DESC']
  243. ]
  244. })
  245. .then(post => {
  246. if (post) {
  247. post.updateAttributes({
  248. [key]: value
  249. })
  250. .then(updatedPost => {
  251. if (cb) {
  252. cb()
  253. }
  254. res.json({
  255. message: 'You have successfully updated it!'
  256. })
  257. })
  258. .catch(err => console.log(err.message));
  259. } else {
  260. const err = new Error('You should have one post for that number');
  261. res.status(404).json({
  262. message: err.message
  263. });
  264. }
  265. })
  266. .catch(err => console.log(err.message));
  267. }
  268.  
  269. const sendTextMessage = (res, nextStep, message, phone, viewing = false) => () => {
  270. // const phoneBook= {
  271. // "+1858262332": 1,
  272. // "+11234567123": 3,
  273. // }
  274. phoneBook[phone] = { nextStep, viewing: viewing || phoneBook[phone].viewing };
  275. client.messages.create({
  276. body: message, // here is your text message
  277. to: phone, // replace this with user's phone number
  278. from: '+12544002317',
  279. })
  280. .then((message) => {
  281. console.log(`Yay! Message ${message.toString()} sent to phone ${phone}!`)
  282. res.end();
  283. }).catch(err => {
  284. console.log(err)
  285. })
  286. }
  287.  
  288. //!!!Why doesn't the models all require sequalize!!
  289. //first question ;;;
  290. //create a post using the users phone number
  291. //put reponse to the post
  292. //and for the other qustions this stuff updates the listings
  293. //step 1; find a post by their phone number
  294. //
  295. //step2; update the post data according to the response
  296. // understand inlude
  297. // you can filter an unfinished post out, .filter for an array
  298. //ex case name find the user, update the name for whatever the user replied.
  299. //
  300. // router.post('/posts', function (req, res) {
  301. // const post = req.body.post;
  302. // const userId = req.body.userId;
  303. // post.UserId = userId;
  304. // db.JobPost.create(post)
  305. // .then(post => res.json(post))
  306. // .catch(err => res.status(500).json(err))
  307. // });
  308.  
  309. // user.findOrCreate() user.update name name
  310.  
  311. // jobPost.findorCreate jobPost.update role: {]}
  312.  
  313. // router.post('/textit/:question/create', function (req, res) {
  314. // var value = req.body.text;
  315. // var phone = req.body.phone;
  316. // const userId = req.body.phone;
  317. // post.UserId = userId;
  318. // var question = req.params.question;
  319.  
  320. // switch (question) {
  321. // case 'role':
  322. // //use sequalize to create the user and add the phone from the text it
  323.  
  324. // var ref = db.child('users').child(value).child(phone).push({role: value});
  325. // contacts[phone].role = value;
  326. // contacts[phone].id = ref.key();
  327.  
  328. // //create.user
  329. // //
  330. // break;
  331. // case 'name':
  332. // database.ref().child('users')
  333. // .child(contacts[phone].role || 'employee').child(phone).child(contacts[phone].id).update({name: value})
  334. // break;
  335. // case 'location':
  336. // database.ref().child('users')
  337. // .child(contacts[phone].role || 'employee').child(phone).child(contacts[phone].id).update({location: value})
  338. // break;
  339. // case 'skills':
  340. // database.ref().child('users')
  341. // .child(contacts[phone].role || 'employee').child(phone).child(contacts[phone].id).update({skills: value})
  342. // break;
  343. // case 'hourly':
  344. // database.ref().child('users')
  345. // .child(contacts[phone].role || 'employee').child(phone).child(contacts[phone].id).update({hourly: value})
  346. // break;
  347. // }
  348. // db.JobPost.create(post)
  349. // //i believe this is the spot i would put the filter for a complete form before posting
  350. // .then(post => res.json(post))
  351. // .catch(err => res.status(500).json(err));
  352.  
  353. // // Get name
  354. // // Send it firebase
  355. // res.end();
  356. // })})
  357.  
  358. router.get('/user', function (req, res) {
  359. var role = req.query.role;
  360. var phone = req.query.phone;
  361. db.User.findAll({
  362. where: {
  363. role: role || {
  364. $ne: null
  365. },
  366. phone: phone || {
  367. $ne: null
  368. },
  369. }
  370. })
  371. .then((users) => {
  372. res.json(users);
  373. })
  374. })
  375.  
  376. // id
  377. router.get('/user/:id', function (req, res) {
  378. var id = req.params.id;
  379. db.User.findById(id)
  380. .then((user) => {
  381. res.json(user);
  382. })
  383. })
  384.  
  385. // create a user
  386. router.post("/user", function (req, res) {
  387. console.log(req.body);
  388. db.User.create(req.body)
  389. .then(function (user) {
  390. res.json(user);
  391. }).catch(function (err) {
  392. res.json(err);
  393. })
  394. })
  395.  
  396. // update a user
  397. router.put("/user/:id", function (req, res) {
  398. var id = req.params.id;
  399. db.User.update(
  400. req.body, {
  401. //why a comma after body?
  402. //the answer is because req.body, {} are arguments inside teh function update
  403. where: {
  404. id: id
  405. }
  406. })
  407. .then(function (result) {
  408. // When updating with Sequelize, it will return us an array that only
  409. // contains one item. This item will only be either 1 or 0.
  410. // 1 stands for success
  411. // 0 means fuck off
  412. if (result[0]) {
  413. res.json({
  414. message: `Successfully updated user ${id}`
  415. });
  416. } else {
  417. res.status(403).json({
  418. message: `There is no such as user ${id}! You liar!`
  419. });
  420. }
  421. })
  422. .catch((err) => {
  423. res.status(500).json(err)
  424. })
  425. })
  426.  
  427.  
  428. // delete a user
  429. router.delete("/user/:id", function (req, res) {
  430. var id = req.params.id;
  431. db.User.destroy({
  432. where: {
  433. id: id
  434. }
  435. })
  436. .then(function (result) {
  437. console.log(result)
  438. if (result) {
  439. res.json({
  440. message: `Successfully deleted user ${id}`
  441. });
  442. } else {
  443. res.status(403).json({
  444. message: `There is no such as user ${id}! You fibber!`
  445. });
  446. }
  447. })
  448. .catch((err) => {
  449. res.status(500).json(err)
  450. })
  451. });
  452.  
  453. // Posts APIs
  454. router.get('/posts', function (req, res) {
  455. db.JobPost.findAll({
  456. include: [{
  457. model: db.User,
  458. attributes: {
  459. exclude: ['password']
  460. }
  461. }]
  462. })
  463. .then((posts) => {
  464. const filteredPosts = posts.filter(post => post.hasFinishedCreation());
  465. res.json(filteredPosts);
  466. })
  467. .catch(err => res.status(500).json(err))
  468. });
  469.  
  470. router.post('/posts', function (req, res) {
  471. const post = req.body.post;
  472. const userId = req.body.userId;
  473. post.UserId = userId;
  474. db.JobPost.create(post)
  475. .then(post => res.json(post))
  476. .catch(err => res.status(500).json(err))
  477. });
  478.  
  479. router.post('/register', function (req, res) {
  480. const user = req.body.user;
  481. console.log(req.body);
  482. db.User.create(user)
  483. .then(user => {
  484. delete user.dataValues.password;
  485. res.json(user)
  486. })
  487. .catch(err => res.status(500).json(err))
  488. })
  489.  
  490. router.post('/login', function (req, res) {
  491. const email = req.body.email;
  492. const password = req.body.password;
  493. db.User.findOne({
  494. where: {
  495. email
  496. }
  497. })
  498. .then(user => {
  499. if (user.password !== password) {
  500. res.status(401).json({
  501. message: 'You ain\'t no master'
  502. })
  503. }
  504. delete user.dataValues.password;
  505. res.json(user);
  506. })
  507. .catch(err => res.status(500).json(err))
  508. })
  509.  
  510.  
  511. // router.get('/index', function (){
  512. // res.send('/index.html')
  513. // })
  514. module.exports = router;
Add Comment
Please, Sign In to add comment