Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Finished version 1.0

  • Loading branch information...
commit c625b224591aee8e41e9d45797ed9be73d49816a 1 parent ab1c0ba
@toantran authored
Showing with 478 additions and 1,871 deletions.
  1. +6 −0 app.js
  2. +3 −0  coffee/app.coffee
  3. +21 −0 coffee/public/js/data.coffee
  4. +65 −3 coffee/public/js/index.coffee
  5. +0 −5 coffee/public/js/news.coffee
  6. +0 −58 coffee/public/js/team.coffee
  7. +0 −27 coffee/public/js/todochallenge.coffee
  8. +0 −12 coffee/public/js/todoinvite.coffee
  9. +0 −19 coffee/public/js/todomatch.coffee
  10. +0 −18 coffee/public/js/todoteam.coffee
  11. +6 −8 coffee/repository/base.coffee
  12. +0 −18 coffee/repository/matches2.coffee
  13. +0 −18 coffee/repository/news.coffee
  14. +0 −50 coffee/repository/teams2.coffee
  15. +46 −1 coffee/routes/index.coffee
  16. +56 −0 coffee/services/customer.coffee
  17. +0 −398 coffee/services/match.coffee
  18. +0 −69 coffee/services/news.coffee
  19. +0 −261 coffee/services/post.coffee
  20. +0 −669 coffee/services/team.coffee
  21. +29 −0 public/js/data.js
  22. +69 −5 public/js/index.js
  23. +0 −43 public/js/todochallenge.js
  24. +0 −19 public/js/todoinvite.js
  25. +0 −27 public/js/todomatch.js
  26. +0 −24 public/js/todoteam.js
  27. +0 −3  public/stylesheets/style.less
  28. +7 −9 repository/base.js
  29. +62 −6 routes/index.js
  30. +74 −0 services/customer.js
  31. +0 −96 services/news.js
  32. +7 −0 views/customer.jade
  33. +26 −0 views/data.jade
  34. +1 −5 views/index.jade
View
6 app.js
@@ -71,12 +71,18 @@
}
};
+ app.get('/data', restrict, routes.data);
+
+ app.get('/customers', restrict, routes.customers);
+
app.get('/login', routes.login);
app.get('/logout', routes.logout);
app.post('/login', routes.authenticate);
+ app.post('/customeradd', restrict, routes.customeradd);
+
app.get('/', restrict, routes.index);
app.listen(3000);
View
3  coffee/app.coffee
@@ -55,9 +55,12 @@ restrict = (req, res, next) ->
# Routes
+app.get '/data', restrict, routes.data
+app.get '/customers', restrict, routes.customers
app.get '/login', routes.login
app.get '/logout', routes.logout
app.post '/login', routes.authenticate
+app.post '/customeradd', restrict, routes.customeradd
app.get '/', restrict, routes.index
View
21 coffee/public/js/data.coffee
@@ -0,0 +1,21 @@
+jQuery ($) ->
+ makethis = -> @
+
+ global = makethis.call()
+ global.setActiveMenu 1
+
+ formsubmit = ->
+ formdata = {}
+
+ for item in $(@).serializeArray()
+ do (item) ->
+ formdata[item.name] = item.value
+
+ $.post('customeradd', formdata)
+ .success (data) ->
+ if data?.success
+ console.log 'OK'
+
+ return false
+
+ $('form#customer-form').on 'submit', formsubmit
View
68 coffee/public/js/index.coffee
@@ -1,10 +1,72 @@
jQuery ($) ->
+
+ buildDetailInfo = (customer) ->
+ contentString = '<div class="alert alert-info">' +
+ '<div>' +
+ '<strong>Name: </strong>' + customer?.name +
+ '</div>' +
+ '<div>' +
+ '<strong>Contact: </strong>' + customer?.contact +
+ '</div>' +
+ '<div>' +
+ '<strong>Address: </strong>' + customer?.address +
+ '</div>' +
+ '</div>'
+
+
+ popLatLong = (customer, callback = ->) ->
+ if customer?.latlng?
+ callback customer
+ else if customer?.lat? and customer?.lng?
+ customer.latlng = new google.maps.LatLng(customer?.lat, customer?.lng, true)
+ callback customer
+ else
+
+ @geo.geocode
+ address: customer?.address
+ , (results, status) ->
+ if status is google.maps.GeocoderStatus.OK
+ customer?.latlng = results[0].geometry.location
+ callback customer
+
+
+ createMarker = (customer, map) ->
+ if customer?.latlng?
+ marker = new google.maps.Marker({map: map, position: customer?.latlng, title: customer.name, visible: true})
+
+ contentString = buildDetailInfo customer
+
+ google.maps.event.addListener marker, 'click', (e) =>
+ @infoWindow?.close()
+ @infoWindow?.setContent contentString
+ @infoWindow.open map, marker
+
+
+
+ displayCustomer = (customer) ->
+ popLatLong customer, (cust) ->
+ marker = createMarker cust, @map
+
+
+
+ loadCustomers = ->
+ $.get('customers')
+ .success (data) ->
+
+ if data?.success
+ displayCustomer customer for customer in data?.customers
+
+
initialize = ->
mapOptions =
- center: new google.maps.LatLng(-34.397, 150.644)
- zoom: 16
+ center: new google.maps.LatLng(10.80800, 106.67268)
+ zoom: 12
mapTypeId: google.maps.MapTypeId.ROADMAP
- map = new google.maps.Map( document.getElementById("map_canvas"), mapOptions )
+ @map = new google.maps.Map( document.getElementById("map_canvas"), mapOptions )
+ @geo = new google.maps.Geocoder()
+ @infoWindow = new google.maps.InfoWindow()
+
+ google.maps.event.addListener @map, 'tilesloaded', loadCustomers
initialize()
View
5 coffee/public/js/news.coffee
@@ -1,5 +0,0 @@
-jQuery ($) ->
- makethis = -> @
-
- global = makethis.call()
- global.setActiveMenu 4
View
58 coffee/public/js/team.coffee
@@ -1,58 +0,0 @@
-jQuery ($) ->
- makethis = -> @
-
- global = makethis.call()
- global.setActiveMenu 1
-
- ids = {}
-
- $('#team-challenge-dlg').modal
- backdrop: true
- keyboard: true
- show: false
-
- $('#team-joining-dlg').modal
- backdrop: false
- keyboard: true
- show: false
-
- $('#team-challenge-sent-dlg').modal
- backdrop: true
- keyboard: true
- show: false
-
- $('#team-challenge-dlg').on 'show', ->
- $('#team-challenge-dlg .alert-container').empty()
-
- $('button.btn.btn-danger').on 'click', ->
- ids.challengerid = $(@).attr('challengerid')
- ids.challengeeteamid = $(@).attr('challengeeteamid')
- $('#team-challenge-dlg').modal 'show'
-
- $('button.btn.btn-success').on 'click', ->
- teamid = $(@).attr('data-teamid')
- playerid = $(@).attr('data-playerid')
- $.post("/team/#{teamid}/join", playerid: playerid)
- .success (data) ->
- $('#team-joining-dlg').modal 'show'
-
-
- $('#team-challenge-dlg a.btn.btn-primary').on 'click', ->
- values = ids
- form = $('form#team-challenge-form')
- $.each form.serializeArray(), (i, field) ->
- values[field.name] = field.value
-
- $.post('/team/challenge', values)
- .success (data) ->
- if data.success
- $('#team-challenge-dlg').modal 'hide'
- $('#team-challenge-sent-dlg').modal 'show'
- else
- $('#team-challenge-dlg .alert-container')
- .empty()
- .append '<div class="alert alert-error"><a class="close" data-dismiss="alert">x</a><h4>Error!</h4>' + data.error + '</div>'
-
- $('#team-challenge-sent-dlg a.btn.btn-primary').on 'click', ->
- $.publish 'Challenge', 'Blah blah blah'
-
View
27 coffee/public/js/todochallenge.coffee
@@ -1,27 +0,0 @@
-jQuery ($) ->
-
- onbuttonclick = ->
- btnVal = $(@).attr 'value'
- teamid = $(@).attr 'data-teamid'
- otherteamid = $(@).attr 'data-otherteamid'
- btn = $(@)
-
- switch btnVal
- when 'accept'
- url = '/team/challengeaccept'
- data = challengingteamid: otherteamid, challengedteamid: teamid
- when 'decline'
- url = '/team/challengedecline'
- data = challengingteamid: otherteamid, challengedteamid: teamid
- when 'cancel'
- url = '/team/challengecancel'
- data = challengingteamid: teamid, challengedteamid: otherteamid
-
- $.post(url, data)
- .success (resp) =>
- if resp?.success
- $(btn).closest('.alert').alert 'close'
-
- $('button').on 'click', onbuttonclick
-
-
View
12 coffee/public/js/todoinvite.coffee
@@ -1,12 +0,0 @@
-jQuery ($) ->
- accceptinviteclick= (e) ->
- teamid = $(@).attr('data-teamid')
- userid = $(@).attr('data-userid')
-
- $.post('/player/acceptinvite', {userid, teamid})
- .success (data) ->
- window.location.href = window.location.href
- .error (res, status) ->
-
-
- $('.todo-invite a.btn-primary').on 'click', accceptinviteclick
View
19 coffee/public/js/todomatch.coffee
@@ -1,19 +0,0 @@
-jQuery ($) ->
-
- onresultbtnclick = ->
- matchid = $(@).attr 'data-matchid'
- teamid = $(@).attr 'data-teamid'
- playerid = $(@).attr 'data-playerid'
- vote = $(@).attr 'data-vote'
-
- $.ajax
- url: '/match/' + matchid
- type: 'PUT'
- data:
- teamid: teamid
- playerid: playerid
- result: vote
- success: (data) ->
- window.location.href = window.location.href
-
- $('.todo-match button').on 'click', onresultbtnclick
View
18 coffee/public/js/todoteam.coffee
@@ -1,18 +0,0 @@
-jQuery ($) ->
-
- oncreateteamclick = ->
- profileid = $(@).attr 'data-profileid'
- values =
- profileid: profileid
- form = $('form#form-teamcreate')
- $.each form.serializeArray(), (i, field) ->
- values[field.name] = field.value
-
- $.post("/team/#{profileid}", values)
- .success (data) ->
- $(@).closest('modal').modal 'hide'
- $('.todo-noteam.alert').hide()
- window.location.href = window.location.href
-
-
- $('#todo-noteam-create a.btn.btn-primary').on 'click', oncreateteamclick
View
14 coffee/repository/base.coffee
@@ -44,15 +44,13 @@ Return the default DB
###
exports.getDb = getDb = ->
m_refcount++
- if m_db?
- m_db
- else
+ if not m_db?
m_db = new Db dbName, new Server(host, port, {}), native_parser:false
- close = m_db.close
- m_db.close = ->
- m_db.close = close
- closeDb()
- m_db
+ close = m_db.close
+ m_db.close = ->
+ m_db.close = close
+ closeDb()
+ m_db
View
18 coffee/repository/matches2.coffee
@@ -1,18 +0,0 @@
-baseDb = require('./base')
-baseRepo = new baseDb.repository('matches')
-
-{Db, ObjectId, Timestamp, Connection, Server, checkError, errorHandler, getDb} = baseDb
-
-exports.create = () ->
- baseRepo.create.apply baseRepo, arguments
-exports.read = () ->
- baseRepo.read.apply baseRepo, arguments
-exports.update = () ->
- baseRepo.update.apply baseRepo, arguments
-exports.save = () ->
- baseRepo.save.apply baseRepo, arguments
-exports.remove = () ->
- baseRepo.remove.apply baseRepo, arguments
-exports.getById = () ->
- baseRepo.getById.apply baseRepo, arguments
-exports.ObjectId = ObjectId
View
18 coffee/repository/news.coffee
@@ -1,18 +0,0 @@
-baseDb = require('./base')
-baseRepo = new baseDb.repository('news')
-
-{Db, ObjectId, Timestamp, Connection, Server, checkError, errorHandler, getDb} = baseDb
-
-exports.create = () ->
- baseRepo.create.apply baseRepo, arguments
-exports.read = () ->
- baseRepo.read.apply baseRepo, arguments
-exports.update = () ->
- baseRepo.update.apply baseRepo, arguments
-exports.save = () ->
- baseRepo.save.apply baseRepo, arguments
-exports.remove = () ->
- baseRepo.remove.apply baseRepo, arguments
-exports.getById = () ->
- baseRepo.getById.apply baseRepo, arguments
-exports.ObjectId = ObjectId
View
50 coffee/repository/teams2.coffee
@@ -1,50 +0,0 @@
-baseDb = require('./base')
-baseRepo = new baseDb.repository('teams')
-
-{Db, ObjectId, Timestamp, Connection, Server, checkError, errorHandler, getDb} = baseDb
-
-exports.create = () ->
- baseRepo.create.apply baseRepo, arguments
-exports.read = () ->
- baseRepo.read.apply baseRepo, arguments
-exports.update = () ->
- baseRepo.update.apply baseRepo, arguments
-exports.save = () ->
- baseRepo.save.apply baseRepo, arguments
-exports.remove = () ->
- baseRepo.remove.apply baseRepo, arguments
-exports.getById = () ->
- baseRepo.getById.apply baseRepo, arguments
-exports.ObjectId = ObjectId
-
-
-exports.removeChallenge = ( teamid, otherteamid, callback = ->) ->
- console.assert teamid, 'teamid cannot be null'
- throw 'teamid cannot be null' if not teamid
- console.assert otherteamid, 'otherteamid cannot be null'
- throw 'otherteamid cannot be null' if not otherteamid
-
- teamid = new ObjectId(teamid) if typeof teamid is 'string'
- otherteamid = new ObjectId(otherteamid) if typeof otherteamid is 'string'
-
- findObj =
- _id: teamid
- removingLog =
- type: 'challengeremoved'
- data:
- teamid: otherteamid
- createdat: new Date()
- updateObj =
- $set:
- updatedat: new Date()
- $pull:
- challenges:
- teamid: otherteamid
- $addToSet:
- logs: removingLog
-
- try
- baseRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- callback e
View
47 coffee/routes/index.coffee
@@ -1,5 +1,50 @@
+exports.customeradd = (req, res, next) ->
+ customersvc = require '../services/customer'
+
+ customername = req.param 'customername', ''
+ customercontact = req.param 'customercontact', ''
+ customeraddress = req.param 'customeraddress', ''
+
+ try
+ customersvc.add {name:customername, contact: customercontact, address:customeraddress, userid: req.user._id}, (err, customer) ->
+ res.send
+ success: !!! (err)
+ customer: customer
+ catch e
+ console.trace e
+ next()
+
+
+exports.data = (req, res, next) ->
+ customersvc = require '../services/customer'
+
+ try
+ customersvc.getAll req.user._id, '', (err, customers) ->
+ res.render 'data'
+ title: 'Where Art Thou - Data'
+ customers: customers
+ catch e
+ console.trace e
+ next()
+
+
+
+exports.customers = (req, res, next) ->
+ filter = req.param 'filter', ''
+ customersvc = require '../services/customer'
+
+ try
+ customersvc.getAll req.user._id, filter, (err, customers) ->
+ res.send
+ success: !!! (err)
+ customers: customers
+ catch e
+ console.trace e
+ next()
+
+
###
GET
URL /account/login
@@ -33,7 +78,7 @@ exports.logout = (req, res, next) ->
exports.authenticate = (req, res, next) ->
req.session.username = username = req.param 'username', ''
req.session.password = password = req.param 'password', ''
- returnUrl = req.param 'returnurl', '/account/profile'
+ returnUrl = req.param 'returnurl', '/'
if not username
req.flash 'error', 'Enter Email'
View
56 coffee/services/customer.coffee
@@ -0,0 +1,56 @@
+repo = require '../repository/customers'
+
+
+exports.add = (customer, callback = ->) ->
+ console.assert customer, 'customer cannot be null or 0'
+ throw 'customer is null or empty' unless customer?
+
+ customer?.userid = new repo.ObjectId(customer?.userid) if customer?.userid? and typeof customer?.userid is 'string'
+
+ try
+ repo.create customer, (err, addedcustomers) ->
+ callback err, addedcustomers?[0]
+ catch e
+ console.trace e
+ throw e
+
+
+exports.getById = (id, callback = ->) ->
+ console.assert id, 'customer id cannot be null or 0'
+ throw 'customer id is null or empty' unless id?
+
+ try
+ repo.getById id, callback
+ catch e
+ console.trace e
+ throw e
+
+
+exports.getAll = (userid, filter, callback = ->) ->
+ console.assert userid, 'userid cannot be null or 0'
+ throw 'userid is null or empty' unless userid?
+
+ userid = new repo.ObjectId(userid) if typeof userid is 'string'
+
+ try
+ repo.read {userid: userid}, (readerr, cursor) ->
+ return callback(readerr) if readerr
+
+ if cursor?
+ cursor.toArray (toarrayerr, customers)->
+
+ customers?.sort (c1, c2) ->
+ if c1?.name < c2?.name then -1 else 1
+
+ db = cursor.db
+ callback.apply null, [toarrayerr, customers]
+ cursor.close()
+ db.close()
+ else
+ callback()
+
+ catch e
+ console.trace e
+ callback e
+
+
View
398 coffee/services/match.coffee
@@ -1,398 +0,0 @@
-matchRepo = require('../repository/matches2')
-
-
-exports.getById = (matchid, callback = ->) ->
- console.assert matchid, 'matchid cannot be null or 0'
- throw 'matchid cannot be null or 0' unless matchid
-
- try
- matchRepo.getById matchid, callback
- catch e
- console.trace e
- throw e
-
-exports.createMatch = (am, callback = ->) ->
- console.assert am, 'Match object cannot be null'
- throw 'Match object cannot be null' unless am?
-
- matchRepo.create am, callback
-
-
-exports.getCompleteMatches = (callback = ->) ->
- query =
- status: 'complete'
- try
- matchRepo.read query, (readErr, cursor) ->
- if readErr?
- callback readErr
- else if cursor?
- cursor.toArray ->
- db = cursor.db
- callback.apply null, arguments
- cursor.close()
- db.close()
- else
- callback()
-
- catch e
- console.log e
- throw e
-
-
-exports.getPendingExpiredMatches = (callback) ->
- query =
- status: 'pending'
- end:
- $lt: new Date()
-
- try
- matchRepo.read query, (readErr, cursor) ->
- if readErr?
- callback readErr
- else if cursor?
- cursor.toArray ->
- db = cursor.db
- callback.apply null, arguments
- cursor.close()
- db.close()
- else
- callback()
-
- catch e
- console.log e
- throw e
-
-exports.setStatus = setStatus = (matchid, status, callback = ->) ->
- console.assert matchid, 'matchid cannot be null or 0'
- throw 'matchid is null or empty' unless matchid?
-
- matchid = new matchRepo.ObjectId( matchid ) if typeof matchid is 'string'
- findObj = _id : matchid
- updateObj =
- $set:
- status: status
- updatedat: new Date()
-
- try
- matchRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- callback e
-
-
-exports.cancel = (am, callback = ->) ->
- utils = require './utils'
- teamSvc = require './team'
- playerSvc = require './user'
-
- makeSetMatchStatus = (status) ->
- (m, cb) ->
- console.time 'Cancelling match id=%s', m._id
- setStatus m._id, status, () ->
- console.timeEnd 'Cancelling match id=%s', m._id
- cb.apply @, arguments
-
-
- makeRemoveTeamsMatch = (teams) ->
- (m, cb = ->) ->
- makeRemoveOneTeamMatch = (m) ->
- (team, cb2 = ->) ->
- console.time 'Removing match from team id=%s', team._id
- teamSvc.cancelMatch team._id, m, () ->
- console.timeEnd 'Removing match from team id=%s', team._id
- cb2.apply @, arguments
-
- console.timeEnd 'Removing match from teams'
- utils.mapAsync teams, makeRemoveOneTeamMatch( m ), () ->
- console.timeEnd 'Removing match from teams'
- cb.apply @, arguments
-
- makeCreatePlayersPost = (teams) ->
- players = []
- for team in teams
- do (team) ->
- players = players.concat team.members
- (m, cb = ->) ->
- makeCreateOnePlayerPost = (m) ->
- (playerid, cb2 = ->) ->
- post =
- type: 'matchcancelled'
- data:
- matchid: String(m._id)
- createdat: new Date()
-
- console.time 'Creating post for player id=%s', playerid
- playerSvc.addPost playerid, post, () ->
- console.timeEnd 'Creating post for player id=%s', playerid
- cb2.apply @, arguments
-
- console.time 'Creating post for players'
- utils.mapAsync players, makeCreateOnePlayerPost(m), () ->
- console.timeEnd 'Creating post for players'
- cb.apply @, arguments
-
- console.time 'Match cancelling'
- utils.seriesAsync [makeSetMatchStatus('cancelled'), makeRemoveTeamsMatch(am.teams), makeCreatePlayersPost(am.teams)], am, (err, result) ->
- console.timeEnd 'Match cancelling'
- callback.apply @, arguments
-
-
-exports.addVote = (matchid, playerid, teamid, result, callback = ->) ->
- console.assert matchid, 'matchid cannot be null or 0'
- throw 'matchid cannot be null or 0' unless matchid
- console.assert playerid, 'playerid cannot be null or 0'
- throw 'playerid cannot be null or 0' unless matchid
- console.assert teamid, 'teamid cannot be null or 0'
- throw 'teamid cannot be null or 0' unless matchid
- console.assert result is 'win' or result is 'lose', 'result must be win or lose'
- throw 'result must be win or lose' unless result is 'win' or result is 'lose'
-
- vote = {playerid, teamid, count: if result is 'win' then 1 else -1}
- matchid = new matchRepo.ObjectId(matchid) if typeof matchid is 'string'
- findObj =
- _id: matchid
- updateObj =
- $addToSet:
- votes: vote
- $set:
- updatedat: new Date()
-
- try
- matchRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- throw e
-
-
-
-exports.countDecisions = (am) ->
- return 0 unless am?.votes?
-
- results = {}
- # initialize the result object
- results[String(am.teams[0]._id)] =
- count: 0
- win: false
- opponentid: String(am.teams[1]._id)
- results[String(am.teams[1]._id)] =
- count: 0
- win: false
- opponentid: String(am.teams[0]._id)
-
- for {teamid, count} in am.votes
- results[teamid].count += count
-
- Math.abs (results[String(am.teams[1]._id)].count - results[String(am.teams[0]._id)].count)
-
-
-
-exports.finalize = (am, callback = -> ) ->
- teamSvc = require './team'
- playerSvc = require './user'
- utils = require './utils'
-
- console.log 'Counting votes'
- return unless am?.teams?.length is 2
-
- results = {}
- # initialize the result object
- results[String(am.teams[0]._id)] =
- count: 0
- win: false
- opponentid: String(am.teams[1]._id)
- results[String(am.teams[1]._id)] =
- count: 0
- win: false
- opponentid: String(am.teams[0]._id)
-
- for {teamid, count} in am?.votes
- results[teamid].count += count
-
- maxCount = Math.max results[String(am.teams[1]._id)].count, results[String(am.teams[0]._id)].count
-
- results[String(am.teams[1]._id)].win = maxCount <= results[String(am.teams[1]._id)].count
- results[String(am.teams[0]._id)].win = maxCount <= results[String(am.teams[0]._id)].count
-
- console.log 'Result '
- for teamid, result of results
- do (teamid, result) ->
- console.log 'team %s count=%d win=%s', teamid, result.count, result.win
-
- news =
- matchid: am?._id
- winningteamid: if results[String(am.teams[1]._id)].win then am.teams[1]._id else am.teams[0]._id
- losingteamid: if results[String(am.teams[1]._id)].win then am.teams[0]._id else am.teams[1]._id
-
- makeSetMatchComplete = () ->
- (m, cb = ->) ->
- console.time "Set match #{m._id} status to complete"
- setStatus m._id, 'complete', (err) ->
- console.timeEnd "Set match #{m._id} status to complete"
- console.log 'Set match status to complete with err %s', err?
- cb.apply @, arguments
-
- makeUpdateTeamStats = () ->
- (m, cb = ->) ->
- for teamid, result of results
- do (teamid, result) ->
- console.time "Team #{teamid} update stats"
- teamSvc.updateStats teamid, result.opponentid, result.win, (err) ->
- console.timeEnd "Team #{teamid} update stats"
- console.log "Team #{teamid} update stats with error #{err}" if err?
- cb.apply @, arguments
-
- makeUpdatePlayersStats = () ->
- players = []
- for team in am.teams
- do (team) ->
- players = players.concat team.members
- console.log 'Player Ids = ', players
-
- makeUpdatePlayerStats = ( teamidByplayerIdFn ) ->
- (playerid, cb2 = ->) ->
- result = results[teamidByplayerIdFn(playerid)]
- console.log "Found result #{result} for player #{playerid}"
- console.time "Updating player #{playerid} stats"
- playerSvc.updateStats playerid, result.opponentid, result.win, () ->
- console.timeEnd "Updating player #{playerid} stats"
- cb2.apply @, arguments
-
- (m, cb = ->) ->
- fn = (playerid) ->
- ids = team._id for team in am.teams when team.members.indexOf(playerid) >= 0
- console.log "Found team #{ids} for player #{playerid}"
- String ids
-
- console.time 'Updating players stats'
- utils.mapAsync players, makeUpdatePlayerStats( fn ), () ->
- console.timeEnd 'Updating players stats'
- cb.apply @, arguments
-
- makeSetTeamMatchComplete = () ->
- (m, cb = ->) ->
- for team in am.teams
- do (team) ->
- console.time "Match #{am._id} Set team #{team._id} match complete"
- teamSvc.setMatchComplete team._id, am, (err) ->
- console.timeEnd "Match #{am._id} Set team #{team._id} match complete"
- console.log "Match #{am._id} Set team #{team._id} match complete with error #{err}" if err?
- cb null
-
- makeCreateNews = () ->
- (m, maincb = ->) ->
- utils.execute( teamSvc.getById, news.winningteamid )
- .then (err, winningteam, cb = ->) ->
- news.winningteamname = winningteam?.teamname
- teamSvc.getById news.losingteamid, cb
- .then (err, losingteam, cb = ->) ->
- news.losingteamname = losingteam?.teamname
-
- newsSvc = require './news'
- newsSvc.createMatchResultNews news, cb
- .then ->
- maincb null, m
-
- utils.seriesAsync [makeSetMatchComplete(), makeUpdateTeamStats(), makeUpdatePlayersStats(), makeSetTeamMatchComplete(), makeCreateNews()], am, () ->
- console.log 'Done!'
-
-
-###
-Finalize a match, silently
-###
-exports.finalizeSilent = (am, callback = -> ) ->
- teamSvc = require './team'
- playerSvc = require './user'
- utils = require './utils'
-
- console.log 'Counting votes'
- return unless am?.teams?.length is 2
-
- results = {}
- # initialize the result object
- results[String(am.teams[0]._id)] =
- count: 0
- win: false
- opponentid: String(am.teams[1]._id)
- results[String(am.teams[1]._id)] =
- count: 0
- win: false
- opponentid: String(am.teams[0]._id)
-
- for {teamid, count} in am.votes
- results[teamid].count += count
-
- maxCount = Math.max results[String(am.teams[1]._id)].count, results[String(am.teams[0]._id)].count
-
- results[String(am.teams[1]._id)].win = maxCount <= results[String(am.teams[1]._id)].count
- results[String(am.teams[0]._id)].win = maxCount <= results[String(am.teams[0]._id)].count
-
- console.log 'Result '
- for teamid, result of results
- do (teamid, result) ->
- console.log 'team %s count=%d win=%s', teamid, result.count, result.win
-
-
- makeSetMatchComplete = () ->
- (m, cb = ->) ->
- console.time "Set match #{m._id} status to complete"
- setStatus m._id, 'complete', (err) ->
- console.timeEnd "Set match #{m._id} status to complete"
- console.log 'Set match status to complete with err %s', err?
- cb.apply @, arguments
-
- makeUpdateTeamStats = () ->
- (m, cb = ->) ->
- for teamid, result of results
- do (teamid, result) ->
- console.time "Team #{teamid} update stats"
- teamSvc.updateStatsSilent teamid, result.opponentid, result.win, (err) ->
- console.timeEnd "Team #{teamid} update stats"
- console.log "Team #{teamid} update stats with error #{err}" if err?
- cb.apply @, arguments
-
- makeUpdatePlayerStats = () ->
- players = []
- for team in am.teams
- do (team) ->
- players = players.concat team.members
- console.log 'Player Ids = ', players
-
- makeUpdatePlayerStats = ( teamidByplayerIdFn ) ->
- (playerid, cb2 = ->) ->
- result = results[teamidByplayerIdFn(playerid)]
- console.log "Found result #{result} for player #{playerid}"
- console.time "Updating player #{playerid} stats"
- playerSvc.updateStatsSilent playerid, result.opponentid, result.win, () ->
- console.timeEnd "Updating player #{playerid} stats"
- cb2.apply @, arguments
-
- (m, cb = ->) ->
- fn = (playerid) ->
- ids = team._id for team in am.teams when team.members.indexOf(playerid) >= 0
- console.log "Found team #{ids} for player #{playerid}"
- String ids
-
- console.time 'Updating players stats'
- utils.mapAsync players, makeUpdatePlayerStats( fn ), () ->
- console.timeEnd 'Updating players stats'
- cb.apply @, arguments
-
- makeSetTeamMatchComplete = () ->
- (m, cb = ->) ->
- for team in am.teams
- do (team) ->
- console.time "Match #{am._id} Set team #{team._id} match complete"
- teamSvc.setMatchComplete team._id, am, (err) ->
- console.timeEnd "Match #{am._id} Set team #{team._id} match complete"
- console.log "Match #{am._id} Set team #{team._id} match complete with error #{err}" if err?
- cb null
-
- utils.seriesAsync [makeSetMatchComplete(), makeUpdateTeamStats(), makeUpdatePlayerStats(), makeSetTeamMatchComplete()], am, () ->
- console.log 'Done!'
-
-
-
-
-
-
-
View
69 coffee/services/news.coffee
@@ -1,69 +0,0 @@
-newsrepo = require '../repository/news'
-
-exports.getNews = (callback = ->) ->
- newsrepo.read {}, (err, cursor) ->
- return callback(err) if err? or not cursor?
- cursor.sort createdat: -1
- cursor.toArray ->
- db = cursor.db
- callback.apply null, arguments
- cursor.close()
- db.close()
-
-exports.getHighlights = (callback = ->) ->
- newsrepo.read {highlight: 1}, (err, cursor) ->
- return callback(err) if err? or not cursor?
- cursor.sort createdat: -1
- cursor.toArray ->
- db = cursor.db
- callback.apply null, arguments
- cursor.close()
- db.close()
-
-
-
-createNewsContent = (tpl, data) ->
- jade = require 'jade'
- fs = require 'fs'
- path = "#{__dirname}/../views/news/#{tpl}.jade"
- str = fs.readFileSync(path, 'utf8')
- fn = jade.compile str,
- filename: path
- pretty: true
- fn data
-
-
-exports.createNews = createNews = (news..., callback = ->) ->
- [newsObj, newsTpl, newsData] = news
-
- if typeof newsObj is 'string'
- [newsTpl, newsData] = [newsObj, newsTpl]
- newsObj =
- newstpl : newsTpl
- newsdata : newsData
-
- newsObj.newstpl ?= newsTpl
- newsObj.newsdata ?= newsData
- newsObj.newsstatus ?= 'active'
- newsObj.newsdate ?= new Date()
-
- if newsObj?.newstpl? and newsObj?.newsdata?
- newsObj.newscontent = createNewsContent newsObj?.newstpl, newsObj?.newsdata
-
- newsrepo.create newsObj, (err, insertedObjs) ->
- insertedNews = insertedObjs?[0]
- callback err, insertedNews
-
-
-exports.createMatchResultNews = (matchdata, callback = ->) ->
- news =
- highlight: 1
- newsdate: new Date()
- newsstatus: 'active'
- newsdata: matchdata
- caption: 'Match Result'
- pictureurl: '/images/matchresult.jpg'
- createNews news, 'matchresult', matchdata, callback
-
-
-
View
261 coffee/services/post.coffee
@@ -1,261 +0,0 @@
-teamsvc = require './team'
-usersvc = require './user'
-matchsvc = require './match'
-utils = require './utils'
-jade = require 'jade'
-fs = require 'fs'
-templates = {}
-
-
-bootTemplate = (file) ->
- path = "#{__dirname}/../views/post/#{file}"
- name = file.replace '.jade', '' # template name
- str = fs.readFileSync(path, 'utf8')
- fn = jade.compile str,
- filename: path
- pretty: true
- templates[name] = fn
-
-
-# Load all post templates from folder view/post
-bootTemplates = () ->
- fs.readdir "#{__dirname}/../views/post/", (err, files) ->
- throw err if err
- bootTemplate file for file in files when file.indexOf('.jade') >= 0
-
-
-bootTemplates()
-
-
-exports.init = ->
-
-
-exports.loadComment = loadComment = (comment, callback = ->) ->
- usersvc.getById comment?.posterid, (err, user) ->
- comment?.pictureurl = user?.pictureurl
- comment?.postername = user?.nickname
- callback null, comment
-
-
-exports.makePostGen = (user) ->
- (post, callback = ->) ->
- return callback(null, post) unless post?
-
- setPictureUrl = (pictureurl) ->
- post.pictureurl = pictureurl
-
- setDesc = (desc) ->
- post.desc = desc
-
- returnback = (err) ->
- if err
- callback err, post
- else
- if post?.comments?.length
- utils.mapAsync post?.comments, loadComment, (commentErr, comments) ->
- post?.comments = comments
- callback commentErr, post
- else
- callback null, post
-
- data =
- playerid: user?._id
- playername: user?.nickname
-
- genDesc = () ->
- if templates[post?.type]?
- setDesc templates[post?.type](data)
-
- switch post.type
- when 'jointeam'
- setPictureUrl user.pictureurl
- teamsvc.getById post?.data?.teamid, (err, team) ->
- data.teamid = team?._id
- data.teamname = team?.teamname
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
- when 'invite'
- utils.execute( usersvc.getById, post?.data?.playerid)
- .then (err, otherplayer, cb = ->) ->
- return returnback(err) if err
-
- setPictureUrl otherplayer?.pictureurl
-
- data.otherplayerid = otherplayer?._id
- data.otherplayername = otherplayer?.nickname
-
- teamsvc.getById post?.data?.teamid, cb
-
- .then (err, team, cb = ->) ->
- return returnback(err) if err
- data.teamid = team?._id
- data.teamname = team?.teamname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'teamjoin'
- teamsvc.getById post?.data?.teamid, (err, team) ->
- return returnback(err) if err
-
- setPictureUrl team?.pictureurl
- data.teamid = team?._id
- data.teamname = team?.teamname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'recruit'
- setPictureUrl user?.pictureurl
- usersvc.getById post?.data?.playerid, (err, otherplayer) ->
- return returnback(err) if err
-
- data.otherplayerid = otherplayer?._id
- data.otherplayername = otherplayer?.nickname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'newteam'
- setPictureUrl user?.pictureurl
-
- teamsvc.getById post?.data?.teamid, (err, team) ->
- return returnback(err) if err
-
- data.teamid = team?._id
- data.teamname = team?.teamname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
- when 'challengecancelled'
- teamsvc.getById post?.data?.teamid, (err, team) ->
- return returnback(err) if err
-
- setPictureUrl team?.pictureurl
- data.teamid = team?._id
- data.teamname = team?.teamname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'teamchallenging', 'challengedeclined', 'challengedeclining', 'challengeremoved', 'challengecancelling'
- setPictureUrl user?.pictureurl
-
- data.matchtype = post?.data?.matchtype
- data.matchmsg = post?.data?.msg
-
- teamsvc.getById post?.data?.teamid, (err, team) ->
- return returnback(err) if err
-
- data.teamid = team?._id
- data.teamname = team?.teamname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'teamchallenged'
- data.matchtype = post?.data?.matchtype
- data.matchmsg = post?.data?.msg
-
- teamsvc.getById post?.data?.teamid, (err, team) ->
- return returnback(err) if err
-
- setPictureUrl team?.pictureurl
- data.teamid = team?._id
- data.teamname = team?.teamname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'newmatch'
- setPictureUrl '/images/match.jpg'
-
- matchsvc.getById post.data.matchid, (err, am) ->
- return returnback(err) if err
-
- data.teamid = am?.teams[0]?._id
- data.teamname = am?.teams[0]?.teamname
- data.otherteamid = am?.teams[1]?._id
- data.otherteamname = am?.teams[1]?.teamname
- data.expirationdt = am?.end
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'post'
- data.postbody = post?.data?.msg
-
- usersvc.getById post?.data?.posterid, (err, poster) ->
- return returnback(err) if err
-
- setPictureUrl poster?.pictureurl
- data.playerid = poster?._id
- data.playername = poster?.nickname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- when 'matchresult'
- setPictureUrl user?.pictureurl
- data.result = post?.data?.result
-
- teamsvc.getById post?.data?.opponentid, (err, team) ->
- return returnback(err) if err
-
- setPictureUrl team?.pictureurl
- data.teamid = team?._id
- data.teamname = team?.teamname
-
- try
- genDesc()
- returnback null
- catch e
- console.trace e
- returnback e
-
- else
- setPictureUrl user?.pictureurl
- setDesc 'N/A'
- returnback null
-
-
View
669 coffee/services/team.coffee
@@ -1,669 +0,0 @@
-newTeamRepo = require '../repository/teams2'
-utils = require './utils'
-userSvc = require './user'
-matchSvc = require './match'
-
-
-exports.getrecords = (teamid, callback = ->) ->
- console.assert teamid, 'teamid cannot be null or 0'
- throw 'teamid is null or empty' unless teamid?
-
- try
- utils.execute( newTeamRepo.getById, teamid )
- .then (err, hostteam, cb = ->) ->
- return callback(err) if err
-
- if hostteam?.records?.length
- utils.mapAsync hostteam?.records, (rec, iteratorcb = ->) ->
- rec?.result = if rec?.data?.result is 'win' then 'W' else 'L'
- rec?.teamid = rec?.data?.opponentid
- newTeamRepo.getById rec?.data?.opponentid, (getteamerr, team) ->
- rec?.teamname = team?.teamname
- iteratorcb getteamerr, rec
- , cb
- else
- cb()
- .then (err, recs, cb = ->) ->
- callback err, recs
-
- catch e
- console.trace e
- callback e
-
-###
-###
-exports.createJoinRequest = (teamid, playerid, callback = ->) ->
- console.assert teamid?, 'teamid cannot be null'
- throw 'teamid cannot be null' unless teamid?
- console.assert playerid?, 'playerid cannot be null'
- throw 'playerid cannot be null' unless playerid?
-
- teamid = new newTeamRepo.ObjectId(teamid) if typeof teamid is 'string'
- findObj =
- _id: teamid
- post =
- type: 'joinrequest'
- data:
- userid: playerid
- createdat: new Date()
- joinRequest =
- requestor: playerid
- updateObj =
- $addToSet:
- joinrequests: joinRequest
- posts: post
- $set:
- updatedat: new Date()
-
- try
- newTeamRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- throw e
-
-###
-Add a match into a team
-###
-exports.addMatch = addMatch = (teamid, am, callback = ->) ->
- console.assert teamid?, 'teamid cannot be null'
- throw 'teamid cannot be null' unless teamid?
- console.assert am?, 'am cannot be null'
- throw 'am cannot be null' unless am?
-
- am.status = 'pending'
- teamid = new newTeamRepo.ObjectId(teamid) if typeof teamid is 'string'
-
- findObj =
- _id: teamid
- updateObj =
- $addToSet:
- matches: am
- $set:
- updatedat: new Date()
-
- try
- newTeamRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- throw e
-
-
-###
-Retrieve an existing challenge
-###
-exports.getChallenge = getChallenge = (teamid, opponentid, callback = ->) ->
- console.assert teamid?, 'teamid cannot be null'
- throw 'teamid cannot be null' unless teamid?
- console.assert opponentid?, 'opponentid cannot be null'
- throw 'opponentid cannot be null' unless opponentid?
-
- teamid = new newTeamRepo.ObjectId(teamid) if typeof teamid is 'string'
- opponentid = new newTeamRepo.ObjectId(opponentid) if typeof opponentid is 'string'
-
- try
- newTeamRepo.read
- _id: teamid
- challenges:
- '$elemMatch':
- teamid: opponentid
- , {}, (err, cursor) ->
- return callback(err) if err
- cursor.toArray ->
- db = cursor.db
- callback.apply null, arguments
- cursor.close()
- db.close()
-
- catch e
- console.trace e
- throw e
-
-
-###
-Add a challenge obj in both teams, as well as the log for teams and players
-###
-exports.createTeamChallenge = (params, callback = ->) ->
- console.assert params?, 'params cannot be null'
- throw 'params cannot be null' unless params?
-
- utils = require './utils'
- userSvc = require './user'
-
- {teamid, msg, matchtype} = params
- teamid = new newTeamRepo.ObjectId(teamid) if typeof teamid is 'string'
- opponentid = null
-
- try
- utils.execute( userSvc.getById, params.opponentplayerid ) # get the opponent player obj
- .then (err, opponentplayer, cb = ->) =>
- # get the existing challenge
- return callback(err) if err
- params.opponentid = opponentid = opponentplayer.team._id
-
- try
- getChallenge teamid, opponentid, cb
- catch e
- console.trace e
- callback e
- .then (err, challenges, cb = ->) ->
- if challenges?.length
- # already challenged
- callback 'Already challenged'
- else
- cb()
- .then (args..., cb = ->) =>
- # create challenge for challenged team
- challenge =
- type: 'challenged'
- message: params.msg
- matchtype: params.matchtype
- teamid: opponentid
-
- findObj = _id : teamid
- challengePost =
- type: 'challenged'
- data: challenge
- createdat: new Date()
-
- updateObj =
- $addToSet:
- challenges: challenge
- posts: challengePost
- $set:
- updatedat: new Date()
-
- try
- newTeamRepo.update findObj, updateObj, {}, cb
- catch e
- console.trace e
- callback e
- .then (err, args..., cb = ->) ->
- # get challenged team
- try
- newTeamRepo.getById teamid, cb
- catch e
- console.trace e
- callback e
- .then (err, @challengedTeam, cb = ->) =>
- # create challenge post for members of challenged team
- for memberid in @challengedTeam?.members
- do (memberid) ->
- post =
- type: 'teamchallenged'
- data: {teamid: opponentid, msg, matchtype }
- createdat: new Date()
-
- try
- userSvc.addPost memberid, post
- catch e
- console.trace e
- cb()
- .then (args..., cb = ->) ->
- # create challenge for challenging team
- challenge =
- type: 'challenging'
- message: msg
- matchtype: matchtype
- teamid: teamid
-
- findObj = _id : opponentid
- challengePost =
- type: 'challenging'
- data: challenge
- createdat: new Date()
-
- updateObj =
- $addToSet:
- challenges: challenge
- posts: challengePost
- $set:
- updatedat: new Date()
- try
- newTeamRepo.update findObj, updateObj, {}, cb
- catch e
- console.trace e
- callback e
- .then (err, args..., cb = ->) ->
- # get challenging team
- try
- newTeamRepo.getById opponentid, cb
- catch e
- console.trace e
- callback e
- .then (err, @challengingTeam, cb = ->) =>
- for memberid in @challengingTeam?.members
- do (memberid) ->
- post =
- type: 'teamchallenging'
- data: {teamid, msg, matchtype }
- createdat: new Date()
-
- try
- userSvc.addPost memberid, post
- catch e
- console.trace e
- cb()
- .then (args..., cb = ->) =>
- # email challenged team's members
- for memberid in @challengedTeam?.members
- do (memberid) =>
- post =
- type: 'teamchallenged'
- teamid: opponentid
- teamname: @challengingTeam?.teamname
- msg: msg
- matchtype: matchtype
-
- try
- userSvc.notifyChallenge memberid, post
- catch e
- console.trace e
- cb()
- .then ->
- callback()
- catch e
- console.trace e
- throw e
-
-
-###
-Create a pending match, add it to both teams, remove the challenge
-###
-exports.acceptChallenge = (inputs, callback = ->) ->
- console.assert inputs?, 'inputs cannot be null'
- throw 'Inputs cannot be null' unless inputs?
-
- teamids = [inputs.challengingteamid, inputs.challengedteamid]
-
- try
- utils.execute( utils.mapAsync, teamids, newTeamRepo.getById ) # get all teams
- .then (err, @teams, cb = ->) =>
- # create match
- return callback(err) if err
- start = new Date()
- end = new Date()
- am =
- start: start
- end: new Date(end.setDate( end.getDate() + 3 )) # ends after 3 days
- status: 'pending'
- teams: teams
- try
- matchSvc.createMatch am, cb
- catch e
- console.trace e
- throw e
- .then (err, ams, cb = ->) =>
- @am = ams?[0]
- return callback(err) if err
- # add match to teams
- try
- utils.mapAsync @teams, (team, cb) =>
- addMatch( team._id, @am, cb )
- , cb
- catch e
- console.trace e
- throw e
- .then (err, args..., cb = ->) ->
- return callback(err) if err
- # remove the challenge from both teams
- try
- newTeamRepo.removeChallenge inputs.challengedteamid, inputs.challengingteamid
- newTeamRepo.removeChallenge inputs.challengingteamid, inputs.challengedteamid
- catch e
- console.trace e
- throw e
- cb()
- .then (err, args..., cb = ->) =>
- return callback(err) if err
- for team in @teams
- do (team) =>
- try
- utils.mapAsync team.members, (memberid, mapcb = ->) =>
- post =
- type: 'newmatch'
- data:
- matchid: String(@am._id)
- createdat: new Date()
-
- try
- userSvc.addPost memberid, post, mapcb
- catch e
- console.trace e
- throw e
- , cb
- catch e
- console.trace e
- throw e
- callback()
- catch e
- console.trace e
- throw e
-
-exports.cancelChallenge = (inputs, callback = ->) ->
- console.assert inputs?, 'inputs cannot be null'
- throw 'Inputs cannot be null' unless inputs?
-
- try
- utils.execute(newTeamRepo.removeChallenge, inputs.challengingteamid, inputs.challengedteamid)
- .then (err, others..., cb = ->) ->
- return callback(err) if err
-
- try
- newTeamRepo.getById inputs.challengingteamid, cb
- catch e
- console.trace e
- callback e
- .then (err, team, cb = ->) ->
- return callback(err) if err
- if Array.isArray(team?.members)
- for memberid in team.members
- do ( memberid ) ->
- post =
- type: 'challengecancelling'
- data:
- teamid: inputs.challengedteamid
- msg: 'Chicken dance'
- createdat: new Date()
- try
- userSvc.addPost memberid, post
- catch e
- console.trace e
- cb()
- .then (err, args..., cb = ->) ->
- return callback(err) if err
-
- try
- newTeamRepo.removeChallenge inputs.challengedteamid, inputs.challengingteamid, cb
- catch e
- console.trace e
- callback e
- .then (err, others..., cb = ->) ->
- console.log 'Step 5', err
- return callback(err) if err
-
- try
- newTeamRepo.getById inputs.challengedteamid, cb
- catch e
- console.trace e
- callback e
- .then (err, team, cb = ->) ->
- return callback(err) if err
- if Array.isArray(team?.members)
- for memberid in team.members
- do (memberid) ->
- post =
- type: 'challengecancelled'
- data:
- teamid: inputs.challengingteamid
- msg: 'Chicken dance'
- createdat: new Date()
-
- try
- userSvc.addPost memberid, post
- catch e
- console.trace e
- callback()
- catch e
- console.trace e
- throw e
-
-
-exports.declineChallenge = (inputs, callback = ->) ->
- console.assert inputs?, 'inputs cannot be null'
- throw 'Inputs cannot be null' unless inputs?
-
- try
- utils.execute(newTeamRepo.removeChallenge, inputs.challengingteamid, inputs.challengedteamid)
- .then (err, others..., cb = ->) ->
- return callback(err) if err
-
- try
- newTeamRepo.getById inputs.challengingteamid, cb
- catch e
- console.trace e
- callback e
- .then (err, team, cb = ->) ->
- return callback(err) if err
- if Array.isArray(team?.members)
- for memberid in team.members
- do ( memberid ) ->
- post =
- type: 'challengedeclined'
- data:
- teamid: inputs.challengedteamid
- msg: 'Chicken dance'
- createdat: new Date()
-
- try
- userSvc.addPost memberid, post
- catch e
- console.trace e
- cb()
- .then (err, args..., cb = ->) ->
- return callback(err) if err
-
- try
- newTeamRepo.removeChallenge inputs.challengedteamid, inputs.challengingteamid, cb
- catch e
- console.trace e
- callback e
- .then (err, others..., cb = ->) ->
- return callback(err) if err
-
- try
- newTeamRepo.getById inputs.challengedteamid, cb
- catch e
- console.trace e
- callback e
- .then (err, team, cb = ->) ->
- return callback(err) if err
- if Array.isArray(team?.members)
- for memberid in team.members
- do (memberid) ->
- post =
- type: 'challengedeclining'
- data:
- teamid: inputs.challengingteamid
- msg: 'Chicken dance'
- createdat: new Date()
-
- try
- userSvc.addPost memberid, post
- catch e
- console.trace e
- callback()
- catch e
- console.trace e
- throw e
-
-
-exports.cancelMatch = (teamid, matchid, callback = ->) ->
- return callback() unless teamid? and teamid isnt 'undefined' and matchid? and matchid isnt 'undefined'
-
- teamid = new newTeamRepo.ObjectId(teamid) if typeof teamid is 'string'
- matchid = new newTeamRepo.ObjectId(matchid) if typeof matchid is 'string'
-
- findObj =
- _id: teamid
- updateObj =
- $pull:
- matches:
- _id: matchid
- $set:
- updatedat: new Date()
-
- try
- newTeamRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- callback e
-
-
-exports.resetStats = (teamid, callback = ->) ->
- console.assert teamid?, 'teamid cannot be null or 0'
- throw 'teamid is null or empty' unless teamid?
-
- teamid = new newTeamRepo.ObjectId( teamid ) if typeof teamid is 'string'
- findObj = _id : teamid
- updateObj =
- $unset:
- stats: 1
- records: 1
-
- try
- newTeamRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- throw e
-
-
-exports.updateStats = (teamid, opponentid, win, callback = ->) ->
- console.assert teamid?, 'teamid cannot be null or 0'
- throw 'teamid is null or empty' unless teamid?
-
- teamid = new newTeamRepo.ObjectId( teamid ) if typeof teamid is 'string'
- opponentid = String opponentid if typeof opponentid isnt 'string'
- findObj = _id : teamid
- incObj = if win then {'stats.win':1} else {'stats.loss': 1}
- statLog =
- id: new newTeamRepo.ObjectId()
- type: 'matchresult'
- data:
- opponentid: opponentid
- result: if win then 'win' else 'lose'
- createdat: new Date()
- updateObj =
- $inc: incObj
- $set:
- updatedat: new Date()
- $addToSet:
- posts: statLog
- records: statLog
-
- try
- newTeamRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- throw e
-
-
-exports.updateStatsSilent = (teamid, opponentid, win, callback = ->) ->
- console.assert teamid?, 'teamid cannot be null or 0'
- throw 'teamid is null or empty' unless teamid?
-
- teamid = new newTeamRepo.ObjectId( teamid ) if typeof teamid is 'string'
- opponentid = String opponentid if typeof opponentid isnt 'string'
- findObj = _id : teamid
- incObj = if win then {'stats.win':1} else {'stats.loss': 1}
- statLog =
- id: new newTeamRepo.ObjectId()
- type: 'matchresult'
- data:
- opponentid: opponentid
- result: if win then 'win' else 'lose'
- createdat: new Date()
- updateObj =
- $inc: incObj
- $addToSet:
- records: statLog
-
- try
- newTeamRepo.update findObj, updateObj, {}, callback
- catch e
- console.trace e
- throw e
-
-
-exports.setMatchComplete = (teamid, am, callback = ->) ->
- return callback() unless teamid? and teamid isnt 'undefined' and am? and am isnt 'undefined'
-
- teamid = new newTeamRepo.ObjectId(teamid) if typeof teamid is 'string'
- matchid = am._id
-
- findObj =
- _id: teamid
- updateObj =
- $addToSet:
- completematches: am
- $pull:
- matches:
- _id: matchid
- $set:
- updatedat: new Date()
-
- try
- newTeamRepo.update findObj, updateObj, {}, callback
- #callback()
- catch e
- console.trace e
- throw e
-
-
-
-
-exports.sortingTeams = (team1, team2) ->
- win1 = team1?.stats?.win ? 0
- loss1 = team1?.stats?.loss ? 0
- total1 = win1 + loss1
- avg1 = if total1 then (win1 / total1) else 0
- win2 = team2?.stats?.win ? 0
- loss2 = team2?.stats?.loss ? 0
- total2 = win2 + loss2
- avg2 = if total2 then (win2 / total2) else 0
-
- if avg1 isnt avg2
- -avg1 + avg2
- else if win1 isnt win2
- -win1 + win2
- else
- loss1 - loss2
-
-
-
-exports.getAll = (availableOnly, callback = ->) ->
- query =
- hidden:
- $ne: 1
-
- if availableOnly
- query.$or = [{members: null}, {members: {$size: 0}}, {members: {$size: 1}}]
- try
- newTeamRepo.read query, (readErr, cursor) ->
- if readErr?
- callback readErr
- else if cursor?
- cursor.toArray ->
- db = cursor.db
- callback.apply null, arguments
- cursor.close()
- db.close()
-
- else
- callback()
-
- catch e
- console.trace e
- throw e
-
-
-exports.getById = (teamid, callback = ->) ->
- console.assert teamid, 'TeamId cannot be null or 0'
- throw 'TeamId cannot be null or 0' unless teamid
-
- newTeamRepo.getById teamid, callback
-
-
-exports.create = (team, args..., callback = ->) ->
- team = teamname : team if typeof team is 'string'
-
- try
- newTeamRepo.create team, callback
- catch e
- console.trace e
- throw e
-
-
-
-
-
-
View
29 public/js/data.js
@@ -0,0 +1,29 @@
+(function() {
+
+ jQuery(function($) {
+ var formsubmit, global, makethis;
+ makethis = function() {
+ return this;
+ };
+ global = makethis.call();
+ global.setActiveMenu(1);
+ formsubmit = function() {
+ var formdata, item, _fn, _i, _len, _ref;
+ formdata = {};
+ _ref = $(this).serializeArray();
+ _fn = function(item) {
+ return formdata[item.name] = item.value;
+ };
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ item = _ref[_i];
+ _fn(item);
+ }
+ $.post('customeradd', formdata).success(function(data) {
+ if (data != null ? data.success : void 0) return console.log('OK');
+ });
+ return false;
+ };
+ return $('form#customer-form').on('submit', formsubmit);
+ });
+
+}).call(this);
View
74 public/js/index.js
@@ -1,15 +1,79 @@
(function() {
jQuery(function($) {
- var initialize;
+ var buildDetailInfo, createMarker, displayCustomer, initialize, loadCustomers, popLatLong;
+ buildDetailInfo = function(customer) {
+ var contentString;
+ return contentString = '<div class="alert alert-info">' + '<div>' + '<strong>Name: </strong>' + (customer != null ? customer.name : void 0) + '</div>' + '<div>' + '<strong>Contact: </strong>' + (customer != null ? customer.contact : void 0) + '</div>' + '<div>' + '<strong>Address: </strong>' + (customer != null ? customer.address : void 0) + '</div>' + '</div>';
+ };
+ popLatLong = function(customer, callback) {
+ if (callback == null) callback = function() {};
+ if ((customer != null ? customer.latlng : void 0) != null) {
+ return callback(customer);
+ } else if (((customer != null ? customer.lat : void 0) != null) && ((customer != null ? customer.lng : void 0) != null)) {
+ customer.latlng = new google.maps.LatLng(customer != null ? customer.lat : void 0, customer != null ? customer.lng : void 0, true);
+ return callback(customer);
+ } else {
+ return this.geo.geocode({
+ address: customer != null ? customer.address : void 0
+ }, function(results, status) {
+ if (status === google.maps.GeocoderStatus.OK) {
+ if (customer != null) customer.latlng = results[0].geometry.location;
+ }
+ return callback(customer);
+ });
+ }
+ };
+ createMarker = function(customer, map) {
+ var contentString, marker,
+ _this = this;
+ if ((customer != null ? customer.latlng : void 0) != null) {
+ marker = new google.maps.Marker({
+ map: map,
+ position: customer != null ? customer.latlng : void 0,
+ title: customer.name,
+ visible: true
+ });
+ contentString = buildDetailInfo(customer);
+ return google.maps.event.addListener(marker, 'click', function(e) {
+ var _ref, _ref2;
+ if ((_ref = _this.infoWindow) != null) _ref.close();
+ if ((_ref2 = _this.infoWindow) != null) _ref2.setContent(contentString);
+ return _this.infoWindow.open(map, marker);
+ });
+ }
+ };
+ displayCustomer = function(customer) {
+ return popLatLong(customer, function(cust) {
+ var marker;
+ return marker = createMarker(cust, this.map);
+ });
+ };
+ loadCustomers = function() {
+ return $.get('customers').success(function(data) {
+ var customer, _i, _len, _ref, _results;
+ if (data != null ? data.success : void 0) {
+ _ref = data != null ? data.customers : void 0;
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ customer = _ref[_i];
+ _results.push(displayCustomer(customer));
+ }
+ return _results;
+ }
+ });
+ };
initialize = function() {
- var map, mapOptions;
+ var mapOptions;
mapOptions = {
- center: new google.maps.LatLng(-34.397, 150.644),
- zoom: 16,
+ center: new google.maps.LatLng(10.80800, 106.67268),
+ zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
- return map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
+ this.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
+ this.geo = new google.maps.Geocoder();
+ this.infoWindow = new google.maps.InfoWindow();
+ return google.maps.event.addListener(this.map, 'tilesloaded', loadCustomers);
};
return initialize();
});
View
43 public/js/todochallenge.js
@@ -1,43 +0,0 @@
-(function() {
-
- jQuery(function($) {
- var onbuttonclick;
- onbuttonclick = function() {
- var btn, btnVal, data, otherteamid, teamid, url,
- _this = this;
- btnVal = $(this).attr('value');
- teamid = $(this).attr('data-teamid');
- otherteamid = $(this).attr('data-otherteamid');
- btn = $(this);
- switch (btnVal) {
- case 'accept':
- url = '/team/challengeaccept';
- data = {
- challengingteamid: otherteamid,
- challengedteamid: teamid
- };
- break;
- case 'decline':
- url = '/team/challengedecline';
- data = {
- challengingteamid: otherteamid,
- challengedteamid: teamid
- };
- break;
- case 'cancel':
- url = '/team/challengecancel';
- data = {
- challengingteamid: teamid,
- challengedteamid: otherteamid
- };
- }
- return $.post(url, data).success(function(resp) {
- if (resp != null ? resp.success : void 0) {
- return $(btn).closest('.alert').alert('close');
- }
- });
- };
- return $('button').on('click', onbuttonclick);
- });
-
-}).call(this);
View
19 public/js/todoinvite.js
@@ -1,19 +0,0 @@
-(function() {
-
- jQuery(function($) {
- var accceptinviteclick;
- accceptinviteclick = function(e) {
- var teamid, userid;
- teamid = $(this).attr('data-teamid');
- userid = $(this).attr('data-userid');
- return $.post('/player/acceptinvite', {
- userid: userid,
- teamid: teamid
- }).success(function(data) {
- return window.location.href = window.location.href;
- }).error(function(res, status) {});
- };
- return $('.todo-invite a.btn-primary').on('click', accceptinviteclick);
- });
-
-}).call(this);
View
27 public/js/todomatch.js
@@ -1,27 +0,0 @@
-(function() {
-
- jQuery(function($) {
- var onresultbtnclick;
- onresultbtnclick = function() {
- var matchid, playerid, teamid, vote;
- matchid = $(this).attr('data-matchid');
- teamid = $(this).attr('data-teamid');
- playerid = $(this).attr('data-playerid');
- vote = $(this).attr('data-vote');
- return $.ajax({
- url: '/match/' + matchid,
- type: 'PUT',
- data: {
- teamid: teamid,
- playerid: playerid,
- result: vote
- },
- success: function(data) {
- return window.location.href = window.location.href;
- }
- });
- };
- return $('.todo-match button').on('click', onresultbtnclick);
- });
-
-}).call(this);
View
24 public/js/todoteam.js
@@ -1,24 +0,0 @@
-(function() {
-
- jQuery(function($) {
- var oncreateteamclick;
- oncreateteamclick = function() {
- var form, profileid, values;
- profileid = $(this).attr('data-profileid');
- values = {
- profileid: profileid
- };
- form = $('form#form-teamcreate');
- $.each(form.serializeArray(), function(i, field) {
- return values[field.name] = field.value;
- });
- return $.post("/team/" + profileid, values).success(function(data) {
- $(this).closest('modal').modal('hide');
- $('.todo-noteam.alert').hide();
- return window.location.href = window.location.href;
- });
- };
- return $('#todo-noteam-create a.btn.btn-primary').on('click', oncreateteamclick);
- });
-
-}).call(this);
View
3  public/stylesheets/style.less
@@ -58,7 +58,6 @@
.clear-float {
clear: both;
}
-<<<<<<< HEAD
.map-container {
width: 100%;
@@ -69,5 +68,3 @@
width: 100%;
height: 100%;
}
-=======
->>>>>>> 1447554d9579db7439cc78d091ebc9563dd26626
View
16 repository/base.js
@@ -58,19 +58,17 @@
exports.getDb = getDb = function() {
var close;
m_refcount++;
- if (m_db != null) {
- return m_db;
- } else {
+ if (!(m_db != null)) {
m_db = new Db(dbName, new Server(host, port, {}), {
native_parser: false
});
- close = m_db.close;
- m_db.close = function() {
- m_db.close = close;
- return closeDb();
- };
- return m_db;
}
+ close = m_db.close;
+ m_db.close = function() {
+ m_db.close = close;
+ return closeDb();
+ };
+ return m_db;
};
/*
View
68 routes/index.js
@@ -1,10 +1,66 @@
+(function() {
-/*
- GET
- URL /account/login
-*/
+ exports.customeradd = function(req, res, next) {
+ var customeraddress, customercontact, customername, customersvc;
+ customersvc = require('../services/customer');
+ customername = req.param('customername', '');
+ customercontact = req.param('customercontact', '');
+ customeraddress = req.param('customeraddress', '');
+ try {
+ return customersvc.add({
+ name: customername,
+ contact: customercontact,
+ address: customeraddress,
+ userid: req.user._id
+ }, function(err, customer) {
+ return res.send({
+ success: !!!err,
+ customer: customer
+ });
+ });
+ } catch (e) {
+ console.trace(e);
+ return next();
+ }
+ };