diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..9d8d516 --- /dev/null +++ b/.babelrc @@ -0,0 +1 @@ +{ "presets": ["es2015"] } diff --git a/.gitignore b/.gitignore index 38cc84f..b95f1ab 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +node_modules +.env + ### API Keys ### *.auth.js @@ -179,3 +182,4 @@ node_modules # compiled files dist +>>>>>>> 567fb62210242b715e97f93bf0d9fbfb4ea50dcb diff --git a/app.js b/app.js new file mode 100644 index 0000000..f630a5b --- /dev/null +++ b/app.js @@ -0,0 +1,64 @@ +var express = require('express'); +var babel = require("babel-core"); +require("babel-register"); +require('dotenv').load() + +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); + +var routes = require('./routes/index'); +var sites = require('./routes/sites'); + +var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'jade'); + +// uncomment after placing your favicon in /public +//app.use(favicon(__dirname + '/public/favicon.ico')); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(cookieParser()); +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', routes); +app.use('/site', sites); + +// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function(err, req, res, next) { + res.status(err.status || 500); + res.render('error', { + message: err.message, + error: {} + }); +}); + + +module.exports = app; diff --git a/bin/www b/bin/www new file mode 100755 index 0000000..ce2abb9 --- /dev/null +++ b/bin/www @@ -0,0 +1,90 @@ +#!/usr/bin/env node + +/** + * Module dependencies. + */ + +var app = require('../app'); +var debug = require('debug')('gstv:server'); +var http = require('http'); + +/** + * Get port from environment and store in Express. + */ + +var port = normalizePort(process.env.PORT || '3000'); +app.set('port', port); + +/** + * Create HTTP server. + */ + +var server = http.createServer(app); + +/** + * Listen on provided port, on all network interfaces. + */ + +server.listen(port); +server.on('error', onError); +server.on('listening', onListening); + +/** + * Normalize a port into a number, string, or false. + */ + +function normalizePort(val) { + var port = parseInt(val, 10); + + if (isNaN(port)) { + // named pipe + return val; + } + + if (port >= 0) { + // port number + return port; + } + + return false; +} + +/** + * Event listener for HTTP server "error" event. + */ + +function onError(error) { + if (error.syscall !== 'listen') { + throw error; + } + + var bind = typeof port === 'string' + ? 'Pipe ' + port + : 'Port ' + port; + + // handle specific listen errors with friendly messages + switch (error.code) { + case 'EACCES': + console.error(bind + ' requires elevated privileges'); + process.exit(1); + break; + case 'EADDRINUSE': + console.error(bind + ' is already in use'); + process.exit(1); + break; + default: + throw error; + } +} + +/** + * Event listener for HTTP server "listening" event. + */ + +function onListening() { + var addr = server.address(); + var bind = typeof addr === 'string' + ? 'pipe ' + addr + : 'port ' + addr.port; + debug('Listening on ' + bind); +} diff --git a/instructions.md b/instructions.md new file mode 100644 index 0000000..7d83d8a --- /dev/null +++ b/instructions.md @@ -0,0 +1,187 @@ + + + + + + + +# GSTV BE Coding Exercise + +1. [Exercise Overview](#exercise-overview) +1. [System Requirements](#system-requirements) +1. [Version Control](#version-control) +1. [JavaScript](#javascript) + +## Exercise Overview +The site - an individual gas station - is the most atomic piece of the GSTV business model - it is at the core of everything we do. Our hardware is installed at the site, advertisers purchase impressions at a site level and schedules are generated on a per-site basis. Thus, keeping accurate information about a site is essential to maintaining business operations. + +We are asking you to build out the ability to create, edit and view hours for a given site. We are focusing on the way you approach the services, and structure the Mongo documents - there is no expectation of a polished UI. **We want you to focus on the server-side aspects of implementing these requirements.** + +This data is used to help us know when to turn on and off hardware, how many times a video asset is expected to play and at its most basic level, whether the site is open when we try to call them. + +A site may have multiple open and close times for a single day. For example they may be open in the morning, but close mid-afternoon and reopen for the after work rush hour. In many cases stations will be open past midnight, but business owners do not necessarily think of this as the next day. + +[Taco Bell](http://s3-media2.fl.yelpcdn.com/bphoto/bzl1SoxoBR-ggedVDlECAA/ls.jpg) is a perfect example of business hours vs. chronological hours - they may be open until 4am on Sunday, but you still think of it as Saturday night. + +#### Creating and Editing Hours +Edit & Create Site hours have the same business rules. The main difference is that on edit the dropdowns and values are prepopulated, while in add they are blank. + +- Format + - For each day of the week + - Day Label + - Full name + - Each day may have one or many time slots + - For each Time Slot + - Open Time + - Dropdown + - Values are in 30 minute increments + - Values are in AM/PM format + - Values + - Start at Midnight and end 11:30 PM + - Close Time + - Dropdown + - Values are in 30 minute increments + - Values are in AM/PM format + - Values + - Start at 12:30 AM and end at 6:00 AM (next day) + - All values past 11:30 PM (values between Midnight and 6:00 AM) should have the text (next day) at the end + - Remove Button + - Open 24 Hours Button + - Add Button + - Close Button + - Submit Button +- Functionality + - Remove Button + - Removes the selected time slot + - If Open 24 Hours + - Removes Open 24 Hours message + - Displays one empty time slot + - Add Button + - Adds an additional time slot to the selected day + - Open 24 Hours Button + - Removes all the time slots if any exist + - Hides Open 24 Hours Button + - Message + - Open 24 Hours + - Close Button + - User is returned to the spot where they opened the wizard and the view not reflect any changes + - Submit Button + - FE Validates values + - Null Validation + - If a start time is entered a close time is required + - If a close time is entered a start time is required + - Submit fails + - Message + - Unable to Create/Update: {itemName} is required. + - Overlap/Duplicate Validation + - If a timeslot for a given day overlaps any other time slots on the same day + - Submit fails + - Message + - Unable to Create/Update: there is at least one overlapping timeslot + - Time Slot Format Validation + - If the start time falls after the end time + - Message + - Unable to Create/Update: The start time must be before the end time + - If the end time falls before the start time + - Message + - Unable to Create/Update: The start time must be before the end time + - If the start time falls on the end time + - Message + - Unable to Create/Update: The start time may not be the same date as the end time + - If FE validation passes + - Submit changes to the BE + - BE validates values + - Null Validation + - If any required items are null + - Submit fails + - Message + - Unable to Create/Update: {itemName} is required. + - Unchanged Data Validation + - If any required items are null + - Submit fails + - Message + - Unable to Update: {itemName} {itemValue} has not been changed. + - Duplicate Validation + - If any required items are null + - Submit fails + - Message + - Unable to Create/Update: {itemName} {itemValue} already exists. + - Malformed Data Validation + - If any required items are null + - Submit fails + - Message + - Unable to Create/Update: {itemName} {itemValue} does not match the expected format. + - Time Slot Format Validation + - If the start time falls after the end time + - Message + - Unable to Create/Update: The start time must be before the end time + - If the end time falls before the start time + - Message + - Unable to Create/Update: The start time must be before the end time + - If the start time falls on the end time + - Message + - Unable to Create/Update: The start time may not be the same date as the end time + - If BE validation passes + - Update Data + - User is returned to the spot where they opened the wizard and the view will reflect changes from the wizard. + +#### Viewing Hours +- Format + - Normal State + - For current date/time + - Open or Closed + - Rules + - If current date and time is within a defined open period, then Open + - If current date and time is not within a defined open period, then Closed + - For each day + - Day Label + - Full name + - If not Open 24 hours + - For each time slot + - Open Time + - Close Time + - If Open 24 hours + - Message + - Open 24 hours + - If Hours are Null + - Message + - Closed + - Edit Site Hours Button + - Empty State + - Message + - There are no site hours for {Site ID}. + - Create Site Hours Button +- Functionality + - Edit Site Hours Button + - Links to Creating/Editing Hours + - Create Site Hours Button + - Links to Creating/Editing Hours + +#### Extra Credit +##### Future Date/Time Open or Closed +Our field operations team often goes to sites for maintenance or upgrades. While creating their schedules it would be helpful to know if a site will be open on a given date and time in the future. + +##### Timezones +GSTV has sites across the US. People from the Detroit main office may be calling sites in California. For that reason it is important to know the open times based upon a given timezone. + +##### Daylight Savings Time +GSTV has sites in Arizona. Arizona does not participate in daylight savings time. For that reason it is important to know the open times based upon a site’s participation in daylight savings. + +## System Requirements +* Node.js `^4.0.0` +* MongoDB `^3.0.0` + +## Version Control +### GitFlow and GithubFlow +We use [GitFlow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow/) on a daily basis - this allows us to build quality control into our development, QA and deployment process. + +We are asking that you use a modified [Github Flow](https://guides.github.com/introduction/flow/) - sometimes referred to as a [feature branch workflow](https://www.atlassian.com/git/tutorials/comparing-workflows/feature-branch-workflow) - methodology instead of GitFlow. Conceptually, GitFlow and Github flow are similar. + +Please fork our repository and use a feature branch workflow while developing your functionality. When you are ready to submit your work make a [pull request against our repository](https://help.github.com/articles/using-pull-requests/). + +## JavaScript +### Standards +We have a work in progress [style guide](https://github.com/davezuko/gstv-javascript-standards) that you can refer to. We don't expect you to strictly adhere to these standards, but they may help provide insight into how our JavaScript is generally structured. + +### Unit Testing +Please feel free to create unit tests - we use [Mocha](https://github.com/mochajs/mocha). diff --git a/lib/logic.js b/lib/logic.js new file mode 100644 index 0000000..4f0eebf --- /dev/null +++ b/lib/logic.js @@ -0,0 +1,247 @@ +import { Sites, Schedules, TimeSlot } from '../models/index.js'; +import moment from 'moment'; +import moment_timezone from 'moment-timezone'; +import ERROR from './validations.js' +/*------ SITE LOGIC ------*/ + +// Create a New Site +export function newSite(obj) { + return Sites.create({ + site_name: obj.site_name, + address: obj.address, + telephone: obj.phone, + timezone: obj.timezone, + schedule: obj.schedule, + },{ runValidators: true }, function(err){ + return err + }) +} + +export function makeNewSchedule(siteId){ + return Schedules.create({site_id: siteId},{ runValidators: true }, + function(err){ + return err + }); +} + + + + +export function addScheduleToSite(siteId, scheduleId) { + return Sites.update( + {_id: siteId}, + { $push: {schedule: schedule._id }}, + { runValidators: true }, function(err){ + return err + } + ) +} + +// Find One Site +export function findSiteById(id) { + return Sites.findOne({_id: id}); +} + +// Find All Sites +export function findAllSites() { + return Sites.find({}); +} + + +/*----- TIMESLOTS LOGIC -----*/ + +//create a new TimeSlot +export function createTimeSlot(scheduleId, open, close) { + return TimeSlot.create({ + schedule_id: scheduleId, + open: open, + close: close + },{ runValidators: true }, function(err){ + return err + }) +} + +// Find One TimeSlot +export function findTimeSlot(id) { + return TimeSlot.findOne({_id: id}) +} + +// Find all TimeSlots in the Hours array. +export function populateHours(scheduleId){ + return findScheduleById(scheduleId).populate('hours') +} + +// Add timeSlot a specific array +export function addTimeslotToDay(time, day){ + switch(day){ + case "sunday": + + break; + case "monday": + + break; + case "tuesday": + + break; + case "wednesday": + + break; + case "thursday": + + break; + case "friday": + + break; + case "saturday": + + break; + } +} + + +// All moment formatting depends on client +// and how they want to store it. + +// Timestamp is already formatted for NOW in 24 format +// EX: For future updates, convert "HH-MM". +// assume input is a concatenated string ex: "1230" => 12:30 +export function formatTimeslot(input){ + return moment(input, "hmm").format("HH:mm") +} + + + +/*------ SCHEDULE LOGIC -------*/ + +//Create a New BLANK Schedule +export function createSchedule(siteId, data, arr){ + return Schedules.create({ + site_id: siteId, + days: { + sunday: { + isOpenAllDay: arr[0], + hours: [] + }, + monday: { + isOpenAllDay: arr[1], + hours: [] + }, + tuesday: { + isOpenAllDay: arr[2], + hours: [] + }, + wednesday: { + isOpenAllDay: arr[3], + hours: [] + }, + thursday: { + isOpenAllDay: arr[4], + hours: [] + }, + friday: { + isOpenAllDay: arr[5], + hours: [] + }, + saturday: { + isOpenAllDay: arr[6], + hours: [] + } + } + }).then(function (schedule) { + return Promise.all([ + createTimeSlot(schedule._id, data['sunday.open'], data['sunday.close']), + createTimeSlot(schedule._id, data['monday.open'], data['monday.close']), + createTimeSlot(schedule._id, data['tuesday.open'], data['tuesday.close']), + createTimeSlot(schedule._id, data['wednesday.open'], data['wednesday.close']), + createTimeSlot(schedule._id, data['thursday.open'], data['thursday.close']), + createTimeSlot(schedule._id, data['friday.open'], data['friday.close']), + createTimeSlot(schedule._id, data['saturday.open'], data['saturday.close']) + ]) + .then(function (days) { + return Schedules.update({_id: schedule._id}, { $push: { + "days.sunday.hours": days[0]._id, + "days.monday.hours": days[1]._id, + "days.tuesday.hours": days[2]._id, + "days.wednesday.hours": days[3]._id, + "days.thursday.hours": days[4]._id, + "days.friday.hours": days[5]._id, + "days.saturday.hours": days[6]._id + }}) + }) + }) +} + +// Find One Schedule +export function findScheduleById(id) { + return Schedules.findOne({_id: id}); +} + +// Find all Schedules in Schedule Array +export function getSchedules(siteId) { + return findSiteById(siteId).populate('schedule') +} + +// Update a Schedule +export function updateSchedule(scheduleId, data) { + console.log('IM HERE') + Promise.all([ + createTimeSlot(scheduleId, data['sunday.open'], data['sunday.close']), + createTimeSlot(scheduleId, data['monday.open'], data['monday.close']), + createTimeSlot(scheduleId, data['tuesday.open'], data['tuesday.close']), + createTimeSlot(scheduleId, data['wednesday.open'], data['wednesday.close']), + createTimeSlot(scheduleId, data['thursday.open'], data['thursday.close']), + createTimeSlot(scheduleId, data['friday.open'], data['friday.close']), + createTimeSlot(scheduleId, data['saturday.open'], data['saturday.close']) + ]).then(function (dayz) { + console.log('PROMISE ALLLING',dayz) + return Schedules.update({_id: scheduleId}, + { + days: { + sunday: { + isOpenAllDay: data['sunday.isOpenAllDay'] || false, + hours: [days[0]._id] + }, + monday: { + isOpenAllDay: data['monday.isOpenAllDay'] || false, + hours: [days[1]._id] + }, + tuesday: { + isOpenAllDay: data['tuesday.isOpenAllDay'] || false, + hours: [days[2]._id] + }, + wednesday: { + isOpenAllDay: data['wednesday.isOpenAllDay'] || false, + hours: [days[3]._id] + }, + thursday: { + isOpenAllDay: data['thursday.isOpenAllDay'] || false, + hours: [days[4]._id] + }, + friday: { + isOpenAllDay: data['friday.isOpenAllDay'] || false, + hours: [days[5]._id] + }, + saturday: { + isOpenAllDay: data['saturday.isOpenAllDay'] || false, + hours: [days[6]._id] + } + } + }, + { runValidators: true }, function(err){ + return err + } + ) + }) +} + + +/* -------- Extra Logic --------*/ + +//// Find Entire Populated Object +export function getFinalObj(siteId){ + return Sites.findOne({_id: siteId}).then(function (site) { + return site.populate('schedule').then(function (obj) { + return obj.populate('hours') + }) + }) +} diff --git a/lib/validations.js b/lib/validations.js new file mode 100644 index 0000000..856e72e --- /dev/null +++ b/lib/validations.js @@ -0,0 +1,56 @@ +/*---- In case you need custom error messages ----*/ +export const ERROR = { + // Unable to Create/Update: {itemName} is required. + ITEM_REQUIRED: function(item){ return `Unable to CREATE/UPDATE ${item}`}, + // Unable to Create/Update: {itemName} {itemValue} already exists. + DUPLICATE_ENTRY: function(item){ return `Unable to CREATE/UPDATE, ${item} already exits.`}, + // Unable to Create/Update: The start time must be before the end time + START_BEFORE_END: function(){ return 'The start time must be before the end time'}, + // Unable to Create/Update: The start time must be before the end time + END_BEFORE_START: function(){ return 'The end time must be earlier than the start'}, + // Unable to Create/Update: The start time may not be the same date as the end time + TIMES_EQUAL: function(){ return 'The start and end times cannot be the same.'} +} + +export var validate = { + +// If any required items are null +// Submit fails +// Message +// Unable to Create/Update: {itemName} is required. + + // A schedule will have default booleans upon creation + // A schedule will have an empty array for TimeSlots upon creation by default + + +// Unchanged Data Validation +// If any required items are null +// Submit fails +// Message +// Unable to Create/Update: {itemName} is required. + + +// Duplicate Validation +// If any required items are null +// Submit fails +// Message +// Unable to Create/Update: {itemName} {itemValue} already exists. + +// Malformed Data Validation +// If any required items are null +// Submit fails +// Message +// Unable to Create/Update: {itemName} {itemValue} does not match the expected format. + + +// Time Slot Format Validation +// If the start time falls after the end time +// Message +// Unable to Create/Update: The start time must be before the end time +// If the end time falls before the start time +// Message +// Unable to Create/Update: The start time must be before the end time +// If the start time falls on the end time +// Message +// Unable to Create/Update: The start time may not be the same date as the end time +} diff --git a/models/index.js b/models/index.js new file mode 100644 index 0000000..ecc2b9c --- /dev/null +++ b/models/index.js @@ -0,0 +1,7 @@ +import mongoose from 'mongoose' + +mongoose.connect("mongodb://" + process.env.MONGOLAB_URI); + +module.exports.Sites = require('./site.js'); +module.exports.Schedules = require('./schedule.js'); +module.exports.TimeSlot = require('./timeSlot.js'); diff --git a/models/schedule.js b/models/schedule.js new file mode 100644 index 0000000..f5013e7 --- /dev/null +++ b/models/schedule.js @@ -0,0 +1,40 @@ +import mongoose from 'mongoose'; +var Schema = mongoose.Schema; + +var scheduleSchema = new mongoose.Schema({ + site_id: { type: String, required: true}, + days: { + sunday: { + isOpenAllDay: {type: Boolean, required: true, enum: [true, false]}, + hours: [{ type: Schema.Types.ObjectId, ref: 'TimeSlot' }] + }, + monday: { + isOpenAllDay: {type: Boolean, required: true, enum: [true, false]}, + hours: [{ type: Schema.Types.ObjectId, ref: 'TimeSlot' }] + }, + tuesday: { + isOpenAllDay: {type: Boolean, required: true, enum: [true, false]}, + hours: [{ type: Schema.Types.ObjectId, ref: 'TimeSlot' }] + }, + wednesday: { + isOpenAllDay: {type: Boolean, required: true, enum: [true, false]}, + hours: [{ type: Schema.Types.ObjectId, ref: 'TimeSlot' }] + }, + thursday: { + isOpenAllDay: {type: Boolean, required: true, enum: [true, false]}, + hours: [{ type: Schema.Types.ObjectId, ref: 'TimeSlot' }] + }, + friday: { + isOpenAllDay: {type: Boolean, required: true, enum: [true, false]}, + hours: [{ type: Schema.Types.ObjectId, ref: 'TimeSlot' }] + }, + saturday: { + isOpenAllDay: {type: Boolean, required: true, enum: [true, false]}, + hours: [{ type: Schema.Types.ObjectId, ref: 'TimeSlot' }] + } + } +}) + +var Schedules = mongoose.model('Schedules', scheduleSchema); + +module.exports = Schedules; diff --git a/models/site.js b/models/site.js new file mode 100644 index 0000000..b75f9e6 --- /dev/null +++ b/models/site.js @@ -0,0 +1,14 @@ +import mongoose from 'mongoose'; +var Schema = mongoose.Schema; + +var siteSchema = new Schema({ + site_name: { type: String, required: true }, + address: {type: String, required: true}, + telephone: {type: Number, required: true}, + owner: {type: String, required: true}, + timezone: {type: String, required: true}, + schedule: [{ type: Schema.Types.ObjectId, ref: 'Schedules' }], +}) +var Sites = mongoose.model('Sites', siteSchema); + +module.exports = Sites; diff --git a/models/timeSlot.js b/models/timeSlot.js new file mode 100644 index 0000000..ce6d643 --- /dev/null +++ b/models/timeSlot.js @@ -0,0 +1,11 @@ +import mongoose from 'mongoose'; + +var timeSlotSchema = new mongoose.Schema({ + schedule_id: {type: String, required: true}, + open: {type: String, required: true}, + close: {type: String, required: true}, +}) + +var TimeSlot = mongoose.model('TimeSlot', timeSlotSchema); + +module.exports = TimeSlot; diff --git a/notes.md b/notes.md new file mode 100644 index 0000000..1fdc963 --- /dev/null +++ b/notes.md @@ -0,0 +1,52 @@ + + +### Exercise: + + Schedule Time Slots for individual locations. + + + Node and MongoDb w/ + - babel + - momentjs + - mongoose + - + ## Intentions for Models: + + ##### Approach 1 - Associations + * Lookup for individual sites would be faster if they maintain a small document structure, with associations to the business schedules. + * Sites can have an array of schedule ObjectIds so a site can have a standard schedule but also holiday schedules that can be cross referenced with date.Now() on load. + * Each Schedule will have the associated site_id as well as either an object structure or array of days. + * Each day will have a Boolean flag for isOpen24, as well as an array of TimeSlot ids. + * TimeSlots will have a reference to the schedule_id as well as open: and close: fields. + * Eaching over Arrays of ids may give more control, but slows lookup time. Using the populate method is faster, but I need to check how to modify on populate, and whether it saves. + + ##### Approach 2 - Single Document + * A single document drastically decreases amount of IO lookup. + * Much heavier document to bring back for each site. If there are 20,000 documents, and each is large, it may be to slow. + * Single doc has a structure that is easy to reason about. + * However this approach means that when viewing all sites, you have brought more information back than needed, heavy payload. + * Much easier to manipulate with one lookup. + * May be less flexible than maintaining arrays of ids. Difficult to add different schedules, but you maintain an array of holidays instead. + + + Overall, I chose to use associations and smaller document sizes, believing that in production you may need more flexibility. That may not be the case however. Depending on business needs, updating and viewing a strict 7 day schedule, may be all that is needed. + + + + ## Routes + + ##### Approach and Challenges + * In production, we would be sending the appropriate JSON back to the client. However here, in order to produce something given two afternoons of work, I skipped the front-end work and rendered standard jade templates just to view the response. + * This was one of the largest problems I faced, which was unfortunate because time was meant to be focused on producing a back end. + * Without sending JSON and having an interactive FE, I found myself unable to work through the features properly. Without a dynamic form, I couldn't accurately or quickly test my routes or produce a proper request body for clean use in DB functions. Time wasted. + + + + ## RETRO and Conclusion + + * Overall I failed to deliver a workable solution, and struggled making design decisions without knowing further requirements or how to handle edge cases. + * This is where team communication is critical. Given that this was a coding exercise/test, I could not work alongside the team, look at their business logic, see their FE, or read through UML diagrams and Schemas. In an actual work environment, given access to those resources, making design decisions as a team make development much easier and faster. + * Getting caught up in the abyss of the unknown, and not making design decisions quickly enough, but the time I had.. time was up and I was unable to + * parse time and date with momentjs + * build and effective contrived FE + * implement validations diff --git a/package.json b/package.json index 74d77ee..d425a69 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,19 @@ { "name": "node-coding-exercise", + "devDependencies": { + "babel-core": "^6.4.5" + }, + "dependencies": { + "babel": "^6.3.26", + "body-parser": "~1.12.4", + "cookie-parser": "~1.3.5", + "debug": "~2.2.0", + "express": "~4.12.4", + "jade": "~1.9.2", + "morgan": "~1.5.3", + "serve-favicon": "~2.2.1" + }, + "version": "0.0.0", "version": "1.0.0", "description": "GSTV coding exercise for BE candidates", "main": "index.js", diff --git a/public/stylesheets/style.css b/public/stylesheets/style.css new file mode 100644 index 0000000..6b30291 --- /dev/null +++ b/public/stylesheets/style.css @@ -0,0 +1,16 @@ +body { + padding: 50px; + font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; + width: 80%; + margin: 0 auto; +} + +a { + color: #00B7FF; +} + + +.siteInfo{ + border: 2px solid black; + height: 5em; +} diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..e69de29 diff --git a/routes/index.js b/routes/index.js new file mode 100644 index 0000000..25a22dd --- /dev/null +++ b/routes/index.js @@ -0,0 +1,38 @@ +// var express = require('express'); +import express from 'express'; +import * as db from '../lib/logic.js'; +import moment from 'moment'; +import moment_timezone from 'moment-timezone'; +var router = express.Router(); +import {Sites, Schedules, TimeSlot} from '../models/index.js'; + +router.get('/', function(req, res, next) { + let obj = { + site_name:'WaWa', + address: "NJ", + phone: 10123252498, + timezone: 'EST', + schedule: [] + } + + db.newSite(obj).then(function (site) { + console.log('first') + db.addScheduleToSite(site._id).then(function () { + console.log('second') + db.getSchedules(site._id).then(function (data) { + console.log(data) + res.render('index', { title: 'GSTV in Action' }); + }) + }) + }) +}); + + +router.get('/gstv', function(req,res,next){ + Schedules.findOne({_id: "56a195b123c3e67633a5f1df"}).then(function (obj) { + res.render('index', { title: 'GSTV HOME'}); + }) +}) + + +module.exports = router; diff --git a/routes/sites.js b/routes/sites.js new file mode 100644 index 0000000..b27d1b0 --- /dev/null +++ b/routes/sites.js @@ -0,0 +1,167 @@ +import moment from 'moment'; +import moment_timezone from 'moment-timezone'; +import express from 'express'; +import * as db from '../lib/logic'; +var router = express.Router(); + +// Get all Sites +router.get('/', function(req,res,next) { + db.findAllSites() + .then(function (sites) { + res.render('allSites', {allSites: sites}) + }) +}) + + + +// Site Page with Schedule +router.get('/:id/schedule', function(req, res, next) { + db.getSchedules(req.params.id) + .then(function (data) { + console.log(data) + let site = data, + weekdays = data.schedule[0]['days']; + res.render('schedule', {site: site, days: weekdays}) + }) +}); + +router.get('/newSchedule', function(req,res,next) { + let x = db.createTimeSlot() + res.send(x) +}) + + +// Form to Update Schedule +router.get('/:id/schedule/new', function(req, res, next) { + let id = req.params.id; + res.render('newSchedule', {site: id}); +}); + +// Post the New/Updated Schedule +router.post('/:id/schedule/new', function(req, res, next) { + let x = req.body; + let id = req.params.id; + let boolArr = [ + x['sunday.isOpenAllDay'], + x['monday.isOpenAllDay'], + x['tuesday.isOpenAllDay'], + x['wednesday.isOpenAllDay'], + x['thursday.isOpenAllDay'], + x['friday.isOpenAllDay'], + x['saturday.isOpenAllDay'] + ] + + db.createSchedule(id, x, boolArr).then(function (schedule) { + console.log('new schedule', schedule) + res.send('MY OBJ', schedule) + }) + + // Promise.all([ + // db.createTimeSlot(id, x['sunday.open'], x['sunday.close']), + // db.createTimeSlot(id, x['monday.open'], x['monday.close']), + // db.createTimeSlot(id, x['tuesday.open'], x['tuesday.close']), + // db.createTimeSlot(id, x['wednesday.open'], x['wednesday.close']), + // db.createTimeSlot(id, x['thursday.open'], x['thursday.close']), + // db.createTimeSlot(id, x['friday.open'], x['friday.close']), + // db.createTimeSlot(id, x['saturday.open'], x['saturday.close']) + // ]).then(function (days) { + // console.log('days') + // db.findSiteById(id) + // .then(function (site) { + // console.log('site', site.schedule[0]) + // Schedules.findOne(site.schedule[0]) + // .then(function (schedule) { + // console.log('update', schedule._id) + // Schedules.update({_id: schedule._id},{ + // $set: { + // days: { + // sunday: { + + // isOpenAllDay: x['sunday.isOpenAllDay'], + // hours: [days[0]._id] + // }, + // monday: { + // isOpenAllDay: x['monday.isOpenAllDay'], + // hours: [days[1]._id] + // }, + // tuesday: { + // isOpenAllDay: x['tuesday.isOpenAllDay'], + // hours: [days[2]._id] + // }, + // wednesday: { + // isOpenAllDay: x['wednesday.isOpenAllDay'], + // hours: [days[3]._id] + // }, + // thursday: { + // isOpenAllDay: x['thursday.isOpenAllDay'], + // hours: [days[4]._id] + // }, + // friday: { + // isOpenAllDay: x['friday.isOpenAllDay'], + // hours: [days[5]._id] + // }, + // saturday: { + // isOpenAllDay: x['saturday.isOpenAllDay'] , + // hours: [days[6]._id] + // } + // } + // } + // }).then(function () { + // console.log('CLOSE') + // res.redirect('/') + // }) + // }) + // }) + + // console.log(days) + // let temp = new Schedules({ + // site_id: req.params.id, + // days: { + // sunday: { + // isOpenAllDay: x['sunday.isOpenAllDay'], + // hours: [days[0]._id] + // }, + // monday: { + // isOpenAllDay: x['monday.isOpenAllDay'], + // hours: [days[1]._id] + // }, + // tuesday: { + // isOpenAllDay: x['tuesday.isOpenAllDay'], + // hours: [days[2]._id] + // }, + // wednesday: { + // isOpenAllDay: x['wednesday.isOpenAllDay'], + // hours: [days[3]._id] + // }, + // thursday: { + // isOpenAllDay: x['thursday.isOpenAllDay'], + // hours: [days[4]._id] + // }, + // friday: { + // isOpenAllDay: x['friday.isOpenAllDay'], + // hours: [days[5]._id] + // }, + // saturday: { + // isOpenAllDay: x['saturday.isOpenAllDay'] , + // hours: [days[6]._id] + // } + // } + // }) + // temp.save() + // }) + + + // console.log(req.body) + // + // db.getSchedules(req.params.id) + // .then(function (data) { + // db.updateSchedule(data.schedule[0]['_id'], req.body) + // }) + // .then(function () { + // res.redirect('/') + // }) +}) + + + +module.exports = router; diff --git a/views/allSites.jade b/views/allSites.jade new file mode 100644 index 0000000..ef30718 --- /dev/null +++ b/views/allSites.jade @@ -0,0 +1,12 @@ +extends layout + +block content + h1 Loop Over all Sites in DB + p Display All Appropriately with links to corresponding id + each site in allSites + a(href='/site/'+site._id+'/schedule')= site.site_name + p= site.address + p= site.telephone + p= site.timezone + p= site.schedule + diff --git a/views/error.jade b/views/error.jade new file mode 100644 index 0000000..51ec12c --- /dev/null +++ b/views/error.jade @@ -0,0 +1,6 @@ +extends layout + +block content + h1= message + h2= error.status + pre #{error.stack} diff --git a/views/index.jade b/views/index.jade new file mode 100644 index 0000000..23f2f1a --- /dev/null +++ b/views/index.jade @@ -0,0 +1,8 @@ +extends layout + +block content + h1= title + p Welcome to #{title} + + input(type="text" id="date" data-format="DD-MM-YYYY" data-template="D MMM YYYY" name="date" value="09-01-2013") + diff --git a/views/layout.jade b/views/layout.jade new file mode 100644 index 0000000..b945f57 --- /dev/null +++ b/views/layout.jade @@ -0,0 +1,7 @@ +doctype html +html + head + title= title + link(rel='stylesheet', href='/stylesheets/style.css') + body + block content \ No newline at end of file diff --git a/views/newSchedule.jade b/views/newSchedule.jade new file mode 100644 index 0000000..34d203c --- /dev/null +++ b/views/newSchedule.jade @@ -0,0 +1,71 @@ +extends layout + +block content + form(action='/site/'+site+'/schedule/new' method='post') + div.form-group + h1 Sunday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='sunday.isOpenAllDay') + label Open + input(type='time' name='sunday.open') + label Close + input(type='time' name='sunday.close') + div.form-group + h1 Monday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='monday.isOpenAllDay') + label Open + input(type='time' name='monday.open') + label Close + input(type='time' name='monday.close') + div.form-group + h1 Tuesday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='tuesday.isOpenAllDay') + label Open + input(type='time' name='tuesday.open') + label Close + input(type='time' name='tuesday.close') + div.form-group + h1 Wednesday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='wednesday.isOpenAllDay') + label Open + input(type='time' name='wednesday.open') + label Close + input(type='time' name='wednesday.close') + div.form-group + h1 Thursday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='thursday.isOpenAllDay') + label Open + input(type='time' name='thursday.open') + label Close + input(type='time' name='thursday.close') + div.form-group + h1 Friday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='friday.isOpenAllDay') + label Open + input(type='time' name='friday.open') + label Close + input(type='time' name='friday.close') + div.form-group + h1 Saturday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='saturday.isOpenAllDay') + label Open + input(type='time' name='saturday.open') + label Close + input(type='time' name='saturday.close') + div.form-group + br + button(type='submit') Submit + diff --git a/views/schedule.jade b/views/schedule.jade new file mode 100644 index 0000000..97c3475 --- /dev/null +++ b/views/schedule.jade @@ -0,0 +1,106 @@ +extends layout + +block content + h1 Schedule in for Sites + + div.siteInfo + h3 #{site.site_name} + h4 #{site.site_address} + h4 #{site.site_timezone} + + + div.siteInfo + h3 Sunday + if days.sunday.isOpenAllDay + h3 Open 24 Hours + else + table + thead + th Open + th Close + tbody + each timeSlot in days.sunday.hours + td= timeSlot.open + td= timeSlot.close + div.siteInfo + h3 Monday + if days.tuesday.isOpenAllDay + h3 Open 24 Hours + else + table + thead + th Open + th Close + tbody + each timeSlot in days.monday.hours + td= timeSlot.open + td= timeSlot.close + div.siteInfo + h3 Tuesday + if days.tuesday.isOpenAllDay + h3 Open 24 Hours + else + table + thead + th Open + th Close + tbody + each timeSlot in days.tuesday.hours + td= timeSlot.open + td= timeSlot.close + div.siteInfo + h3 Wednesday + if days.wednesday.isOpenAllDay + h3 Open 24 Hours + else + table + thead + th Open + th Close + tbody + each timeSlot in days.wednesday.hours + td= timeSlot.open + td= timeSlot.close + div.siteInfo + h3 Thursday + if days.thursday.isOpenAllDay + h3 Open 24 Hours + else + table + thead + th Open + th Close + tbody + each timeSlot in days.thursday.hours + td= timeSlot.open + td= timeSlot.close + div.siteInfo + h3 Friday + if days.friday.isOpenAllDay + h3 Open 24 Hours + else + table + thead + th Open + th Close + tbody + each timeSlot in days.friday.hours + td= timeSlot.open + td= timeSlot.close + div.siteInfo + h3 Saturday + if days.saturday.isOpenAllDay + h3 Open 24 Hours + else + table + thead + th Open + th Close + tbody + each timeSlot in days.saturday.hours + td= timeSlot.open + td= timeSlot.close + + + + diff --git a/views/updateSchedule.jade b/views/updateSchedule.jade new file mode 100644 index 0000000..5356b8c --- /dev/null +++ b/views/updateSchedule.jade @@ -0,0 +1,72 @@ +extends layout + +block content + h1 Update the Site Schedule: + form(action='/site/'+site+'/schedule/update' method='post') + div.form-group + h1 Sunday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='sunday.isOpenAllDay') + label Open + input(type='time' name='sunday.open') + label Close + input(type='time' name='sunday.close') + div.form-group + h1 Monday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='monday.isOpenAllDay') + label Open + input(type='time' name='monday.open') + label Close + input(type='time' name='monday.close') + div.form-group + h1 Tuesday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='tuesday.isOpenAllDay') + label Open + input(type='time' name='tuesday.open') + label Close + input(type='time' name='tuesday.close') + div.form-group + h1 Wednesday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='wednesday.isOpenAllDay') + label Open + input(type='time' name='wednesday.open') + label Close + input(type='time' name='wednesday.close') + div.form-group + h1 Thursday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='thursday.isOpenAllDay') + label Open + input(type='time' name='thursday.open') + label Close + input(type='time' name='thursday.close') + div.form-group + h1 Friday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='friday.isOpenAllDay') + label Open + input(type='time' name='friday.open') + label Close + input(type='time' name='friday.close') + div.form-group + h1 Saturday + h3 TimeSlot 1 + label Open 24Hrs + input(type='checkbox' name='saturday.isOpenAllDay') + label Open + input(type='time' name='saturday.open') + label Close + input(type='time' name='saturday.close') + div.form-group + br + button(type='submit') Submit +