/**
* Created by wangyc on 2015-3-18.
* timetrack.js
*/
var qs = require('querystring');
exports.sendHtml = function (res, html) {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(html));
res.end(html);
};
exports.parseReceivedData = function (req, cb) {
var body = '';
req.setEncoding('utf8');
req.on('data', function (chunk) {
body += chunk;
});
req.on('end', function () {
var data = qs.parse(body);
cb(data);
});
};
exports.actionForm = function (id, path, label) {
var html = '
' +'' +
'' +
'
';return html;
};
exports.add = function (db, req, res) {
exports.parseReceivedData(req, function (work) {
db.query(
"insert into work(hours,date,description) " +
"values(?,?,?)",
[work.hours, work.date, work.description],
function (err) {
console.log(err);
console.log(res);
if (err) throw err,
exports.show(db, res);
}
);
});
};
exports.delete = function (db, req, res) {
exports.parseReceivedData(req, function (work) {
db.query(
"delete from work where id=?",
[work.id],
function (err) {
if (err) throw err;
exports.show(db, res);
}
);
});
};
exports.archive = function (db, req, res) {
exports.parseReceivedData(req, function (work) {
db.query(
"update work set archived=1 where id=?",
[work.id],
function (err) {
if (err) throw err;
exports.show(db, res);
}
);
});
};
exports.show = function (db, res, showArchived) {
var query = "select * from work where archived=? order by date desc ";
var archiveValue = showArchived ? 1 : 0;
db.query(
query,
[archiveValue],
function (err, rows) {
if (err) throw err;
html = showArchived ? ''
: 'Archived work
';
html += exports.workHitlistHtml(rows);//将结果格式化为表格
html += exports.workFormHtml();
exports.sendHtml(res, html);//给用户发送HTML响应
}
);
};
exports.showArchived = function (db, res) {
exports.show(db, res, true);
};
exports.workHitlistHtml = function (rows) {
var html = '
console.log(rows)
for (var i in rows) {
html += '
';html += '
' + rows[i].date + '';html += '
' + rows[i].hours + '';html += '
' + rows[i].description + '';if (!rows[i].archived) {
html += '
' + exports.workArchiveForm(rows[i].id) + '';}
html += '
' + exports.workDeleteForm(rows[i].id) + '';html += '
';}
html += '
';return html;
};
exports.workFormHtml = function () {
var html = '
'
Date(YYYY-MM-DD):
' +'
Hours worked:
' +'
Description:
' +
'
' +'' +
'
';return html;
};
exports.workArchiveForm = function (id) {
return exports.actionForm(id, '/archive', 'Archive');
};
exports.workDeleteForm = function (id) {
return exports.actionForm(id, '/delete', 'Delete');
};