Skip to content

Commit

Permalink
First Init for push
Browse files Browse the repository at this point in the history
  • Loading branch information
mayank.batra committed Jan 19, 2015
0 parents commit f1ce11f
Show file tree
Hide file tree
Showing 17 changed files with 482 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Created by https://www.gitignore.io

### Node ###
# Logs
logs
*.log

# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directory
# https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git-
node_modules

# Debug log from npm
npm-debug.log

14 changes: 14 additions & 0 deletions ToDo
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Client Size Submit Form Checks
Price
Number of players
Max Categories
Min Categories
Server Side checks
Same as above

Check controllers
Check Models

Database level security
Upload to github
Deploy on micro instance
9 changes: 9 additions & 0 deletions bin/www
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env node
var debug = require('debug')('cpd');
var app = require('../server');

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
20 changes: 20 additions & 0 deletions configs/common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

commonMethods ={};

commonMethods.validateTeam = function(team, players) {
var valid = true;
var currentStructure = _.groupBy(team.players, function(id) {
return players[id].type;
});

if (team.players.length != 8) {
valid = false;
}

for (type in currentStructure) {
if (currentStructure[type] == undefined || currentStructure[type] == null || this.type.max[type] < currentStructure[type].length || currentStructure[type].length < this.type.max[type])
valid = false;
}

return valid;
}
20 changes: 20 additions & 0 deletions configs/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
config = {};

config.startingCash = 10000000;

config.type = {};
config.type.min = {};
config.type.max = {};

config.type.min.Batsman = 3;
config.type.max.Batsman = 4;
config.type.min.WicketKeeper = 1;
config.type.max.WicketKeeper = 1;
config.type.min.Bowler = 2;
config.type.max.Bowler = 3;
config.type.min.AllRounder = 1;
config.type.max.AllRounder = 2;

config.maxPlayers = 8;

exports.config = config;
20 changes: 20 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "cpd",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"express": "~4.2.0",
"static-favicon": "~1.0.0",
"morgan": "~1.0.0",
"cookie-parser": "~1.0.1",
"body-parser": "~1.0.0",
"debug": "~0.7.4",
"jade": "~1.3.0",
"mongoose":"*",
"connect-mongo":"*",
"express-session":"*"
}
}
107 changes: 107 additions & 0 deletions public/javascripts/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
'use strict';

var IplApp = angular.module('IplApp', []);


IplApp.controller('TeamController', function($scope, $http, $window) {

$scope.players = _.object(_.map(players, function(player) {
return [player._id, player]
}));
$scope.types = _.chain(players).pluck('type').unique().value();
$scope.types.push("");

if (team == null || team.length == 0) {
$scope.remainingCash = config.startingCash;
$scope.team = {};
$scope.team.players = [];
} else {
$scope.remainingCash = config.startingCash - _.reduce(team.players, function(sum, player) {
return sum + $scope.players[player]['price'];
}, 0);
$scope.team = team;
_.each($scope.team.players, function(player) {
$scope.players[player]['visible'] = false
});
}




$scope.addPlayer = function(player) {
//Disable the player so that it can't be added again to this team
var currentTeam = _.groupBy($scope.team.players, function(id) {
return $scope.players[id].type;
});
var teamSize = $scope.team.players.length;
if ($scope.team.players.length < 8) {
if (currentTeam[player.type] == undefined || currentTeam[player.type] == null || config.type.max[player.type] > currentTeam[player.type].length) {
if ($scope.remainingCash - $scope.players[player._id]['price'] >= 0) {
$scope.players[player._id]['visible'] = false;
$scope.remainingCash = $scope.remainingCash - $scope.players[player._id]['price'];
$scope.team.players.push(player._id);
} else {
$scope.err = "Err: You do not have sufficient cash to purchase this player";
}
} else {
$scope.err ="Err: Number of " + player.type + " more than " + config.type.max[player.type], currentTeam[player.type].length;
}
} else {
$scope.err ="Err: Size of Team more than max";
}

}

$scope.removePlayer = function(player) {
//Disable the player so that it can't be added again to this team
$scope.players[player]['visible'] = true;
$scope.remainingCash = $scope.remainingCash + $scope.players[player]['price'];
var index = $scope.team.players.indexOf(player);
if (index > -1) {
$scope.team.players.splice(index, 1);
}
}

$scope.saveTeam = function() {

var valid = validateTeam($scope.team, $scope.players);

if (valid === true) {
$scope.err = "";
$http.post('/', {
team: $scope.team
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
} else
$scope.err = valid;
}

function validateTeam(team, players) {
var valid = true;
var currentStructure = _.groupBy(team.players, function(id) {
return players[id].type;
});

if(team.name == null || team.name == undefined || team.name =="")
valid = "Please enter a name for the Team."

if (team.players.length != 8) {
valid = "Team size has to be 8 players.";
}

for (var type in currentStructure) {
if (currentStructure[type] == undefined || currentStructure[type] == null || currentStructure[type].length > config.type.max[type] || currentStructure[type].length < config.type.min[type])
valid = "Number of " + type + " has to be between " + config.type.min[type] + " and " + config.type.max[type];
}

return valid;
}

});
6 changes: 6 additions & 0 deletions public/stylesheets/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
body {
}

a {
color: #00B7FF;
}
58 changes: 58 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var expressSession = require('express-session');
var MongoStore = require('connect-mongo')(expressSession);

var routes = require('./server/routes/index');


// Connect to the database on local mongo DB. No uername and password
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cpd');


var app = express();

// view engine setup
//USing Jade instead of HTML
app.set('views', path.join(__dirname, 'server/views'));
app.set('view engine', 'jade');

//INitializing Express libraries as middleware
//For requesy post params, url route matching and cookie reading
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());

//To server static files from public folder
app.use(express.static(path.join(__dirname, 'public')));

//To manage sessions inside mongo itself
app.use(expressSession({
key: 'session',
resave: false,
saveUninitialized: true,
secret: 'COUPONDUNIA',
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

//Adding Routes to the app
app.use('/', routes);



// 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

module.exports = app;
25 changes: 25 additions & 0 deletions server/models/PlayerModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var mongoose = require('mongoose');

var PlayerSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
price: {
type: Number,
require: true
},
type: {
type: String,
enum: ['Batsman', 'Bowler', 'WicketKeeper', "AllRounder"],
require: true
}
});

var PlayerModel = mongoose.model("Player", PlayerSchema);

PlayerModel.findAll = function(callback) {
PlayerModel.find({}, callback);
}

exports.PlayerModel = PlayerModel;
52 changes: 52 additions & 0 deletions server/models/TeamModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
var mongoose = require('mongoose');
var PlayerSchema = require('./PlayerModel');

var TeamSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
players: [{
type: mongoose.Schema.ObjectId,
ref: 'PlayerSchema'
}],
createdOn: Date,
modifiedOn: Date,
session: {
type: String,
required: true
}
});

var TeamModel = mongoose.model("Team", TeamSchema);

TeamSchema.pre('validate', function(next) {
var self = this;
if (this.isNew) {
this.createdOn = Date.now();
}
this.modifiedOn = Date.now();
next();
});

TeamModel.findBySession = function(session, callback) {
TeamModel.findOne({
session: session
}, callback);
}

TeamModel.createTeam = function(team, callback) {
//Add Server Side Validation
TeamModel.create(team, callback);
}

TeamModel.updateTeam = function(id, team, callback) {
// Add Server Side Validation
TeamModel.update({
_id: id
}, team, {
upsert: true
}, callback);
}

exports.TeamModel = TeamModel;
Loading

0 comments on commit f1ce11f

Please sign in to comment.